android textview點選變色 鬆開恢復或不恢復
阿新 • • 發佈:2019-01-26
一、textview 點選變色,鬆開恢復。效果如左圖:
二、鬆開後不恢復。如右圖:
一、textview 點選變色,鬆開恢復
1. 設定clickable屬性為true -----Textview 預設不可點選
android:clickable="true"
2. drawable 檔案下新建 selector 型別 xml 檔案 此處我的命名為 demo_selector
點選 textview 的屬性為 state_pressed,在此檔案下設定
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:color="#3D4245"></item>
<item android:state_pressed="true" android:color="#FF5000"></item>
</selector>
3. 新增引用
<TextView android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content" android:clickable="true" android:textColor="@drawable/demo_selector"/> <TextView
完成。
二、textview 點選變色,鬆開不恢復
此效果我將使用 Radiogroup 控制元件完成,因為自帶選中屬性。
1. 設定佈局
新增 RadioGroup 內含兩個 RadioButton 控制元件
2. drawable 檔案下新建 selector 型別 xml 檔案 此處我的命名為 demo_selector
由於是 RadioButton,不同於 textview ,這裡屬性為 state_checked
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="false" android:color="#3D4245"></item> <item android:state_checked="true" android:color="#FF5000"></item> </selector>
3. 設定 style
開啟values檔案下的styles.xml檔案
新增自己的style
<style name="demoStyle">
<item name="android:button">@null</item>
<item name="android:textSize">17sp</item>
<item name="android:textColor">@drawable/demo_selector</item> //引用selector
</style>
完成。
佈局頁面設定如下:
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:gravity="center"
android:text="價格"
style="@style/demoStyle"/>
<RadioButton
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:layout_height="wrap_content"
android:text="銷量"
style="@style/demoStyle"/>
</RadioGroup>