【Android】linearlayout點擊變換顏色

直接貼代碼:

1. layout中的相關代碼:

    <LinearLayout
        android:id="@+id/llGoodCommentContainer"
        android:orientation="vertical"
        android:layout_weight="1"
        android:gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/layout_selector"
        android:clickable="true"
        >
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/zan"
            android:focusable="false"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="贊!"
            android:textColor="#ffffff"
            android:focusable="false"
            />
    </LinearLayout>

2. drawable/文件夾下的layout_selecter.xml文件,這個文件就是設置點擊時的顏色和默認顯示時的顏色

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:drawable="@color/transparent_red"/>
    <item android:state_pressed="true" android:drawable="@color/transparent_red" />
    <item android:drawable="@color/red"/>
</selector>

3. color.xml文件中的兩個顏色:

<color name="red">#ff5654</color>
<color name="transparent_red">#ddff5654</color>

最後的說明, 我之前這麼弄一直不出效果,後來發現,需要點擊效果的Linearlayout的parent控件我設置了@color/red背景,這樣的話,點擊Linearlayout其實這個LinearLayout是變色的,但是由於@color/transparent_red只是@color/red變換了alpha值的顏色,所以效果被parent控件的顏色覆蓋了,顯示出來的沒有任何效果.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章