在列表视图(Kotlin,Android)中更改所选项目的文本颜色

时间:2019-06-03 13:23:08

标签: android kotlin android-listview onclicklistener textcolor

我的应用程序中有一个列表视图。如何更改所选项目的文本颜色?

例如,我选择一些列表项。其文本颜色应从黑色更改为灰色。 然后,我选择另一个项目。其文字颜色也应从黑色更改为灰色,但第一个元素的文字颜色应再次变为黑色。

我尝试了以下代码,但出现异常:

  

试图在空对象引用上调用虚拟方法'void android.widget.TextView.setText(java.lang.CharSequence)'

QuestionActivity.kt:

var answersList = arrayOf("about", "against", "for", "by")

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_question)

    val selection= findViewById<TextView>(R.id.options)
    val lv = findViewById<ListView>(R.id.variants)
    val prodAdapter = ArrayAdapter<String>(this, R.layout.mytextview, answersList)
    lv.adapter = prodAdapter

    lv.setOnItemClickListener { parent, view, position, id ->
     val selectedItem = parent.getItemAtPosition(position).toString()
     selection.setText(selectedItem)
     selection.setTextColor(Color.DKGRAY)
    }}  

activity_question.xml:

<?xml version="1.0" encoding="utf-8"?>

    <ListView
        android:id="@+id/variants"
        android:divider="#FFFFFF"
        android:layout_width="347dp"
        android:layout_height="254dp" tools:ignore="MissingConstraints"
        app:layout_constraintStart_toStartOf="parent" android:layout_marginLeft="32dp"
        android:layout_marginStart="32dp" app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="32dp"
        android:layout_marginRight="32dp" android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@+id/appBarLayout" android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="@+id/button4"
    />
</android.support.constraint.ConstraintLayout>

mytextview.xml:

<?xml version="1.0" encoding="utf-8"?>

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/options"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:textAppearance="?android:attr/textAppearanceListItemSmall"
      android:gravity="center_vertical"
      android:minHeight="?android:attr/listPreferredItemHeightSmall"
      android:textSize="20dp"
      android:textColor="#000000"
/>

请帮助我解决此问题

1 个答案:

答案 0 :(得分:0)

您必须使用选择器。像这样:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:color ="@color/selected_color" android:state_selected="true"/>
    <item android:color ="@color/pressed_color" android:state_pressed="true"/>
    <item android:color ="@color/default_color"/>

</selector>

然后在项目XML文件中使用选择器:

android:textColor="@color/text_selector"

您可以获取更多信息here