[英]How to make StateListDrawable change background when button is pressed? (in xml)
我正在做Drawables的Google android教程 。 我完成了它,但仍堅持執行此“挑戰”任務:
創建一個Drawable資源,當“按下” ImageButton的狀態時,將ImageButton的背景更改為與邊框相同的顏色。 您還應該將ImageButton元素內文本的顏色設置為一個選擇器,使其在“按下”按鈕時變為白色。
對於styles.xml,請參閱此處以獲取“挑戰”之前的完整教程代碼 ,我修改了ScoreButtons以訪問新的可繪制的button_state
<style name="ScoreButtons" parent="Widget.AppCompat.Button">
<item name="android:background">@drawable/button_state</item>
<item name="android:tint">@color/colorPrimary</item>
</style>
遵循android docs https://developer.android.com/guide/topics/resources/drawable-resource.html#StateList的 drawable / button_state
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@drawable/button_background_pressed"
android:state_pressed="true"
/>
<item
android:drawable="@drawable/button_background_released"
android:state_pressed="false"
/>
</selector>
button_background_pressed.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke
android:width="2dp"
android:color="@color/colorPrimary"/>
android:background="@color/colorPrimary"
</shape>
button_background_released.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<stroke
android:width="2dp"
android:color="@color/colorPrimary"/>
</shape>
按下按鈕時沒有變化。 我想念什么?
在按下的可繪制對象中,需要使用實體元素以所需的顏色填充形狀:
<?xml version="1.0" encoding="utf-8">
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<stroke android:width="2dp" android:color="@color/colorPrimary"/>
<solid android:color="@color/colorPrimary"/>
</shape>
在此處檢查可以包含在Shape元素中的所有可用xml元素。
如果我理解正確,您的button_background_pressed應該看起來像這樣
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="@color/colorPrimary" />
</shape>
如果您的最低版本是android 21,則可以使用Ripple Drawable https://developer.android.com/reference/android/graphics/drawable/RippleDrawable
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.