簡體   English   中英

使用 style.xml 更改 Clicked 和 unClicked 狀態中的 TextView 顏色

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM