[英]Change TextView color in Clicked and unClicked State using style.xml
假设我有一个具有 TextView 和 ImageView 的 cardView 布局。 我在 RecyclerView 中展示了它们。 如果我单击视图 textColor 和可绘制颜色将变为红色。 然后如果我单击另一个视图,该单击的视图将是红色的,而 prevoius 将转换为黑色。 我在 bottomNavigationView 中使用自定义颜色做了同样的事情。
这是布局
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/item_layout_card_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="10dp"
app:cardCornerRadius="4dp"
app:cardElevation="2dp"
app:cardMaxElevation="3dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/item_image_view"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="10dp"
android:scaleType="centerCrop"
android:src="@mipmap/ic_launcher" />
<TextView
android:id="@+id/item_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/item_image_view"
android:layout_centerHorizontal="true"
android:layout_marginBottom="5dp"
android:gravity="center"
android:text="Item"
android:textColor="#000000"
android:textSize="12sp" />
</RelativeLayout>
</android.support.v7.widget.CardView>
您想更改回收站视图行的颜色
在您的适配器中定义变量,如
var coloredIndex = -1
在您的 onBindViewHolder() 函数中
h.var.setOnClickListener {
coloredIndex = curPos
}
changeSelectedItemColor(h, curPos)
在下面定义这个函数来改变颜色。
private fun changeSelectedItemColor(h: YourViewHolder, curPos: Int) {
if (coloredIndex == curPos) {
h.var.setBackgroundColor(ContextCompat.getColor
(context, R.color.red))
} else {
h.var.setBackgroundColor(ContextCompat.getColor
(context, R.color.black))
}
notifyDataSetChanged()
}
这是一个例子。 您没有在问题中添加回收站视图适配器代码。 请添加它以进一步说明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.