gpt4 book ai didi

Android:如何在选中时为按钮绘制不同的背景?

转载 作者:太空狗 更新时间:2023-10-29 16:06:45 25 4
gpt4 key购买 nike

我希望我的 Button 默认使用透明背景绘制,按下时使用深蓝色背景绘制,选中时使用浅蓝色背景绘制。我将按钮的背景设置为下面的选择器,并在单击按钮时调用 Button.setSelected(!Button.isSelected())。按下状态正常工作,但 Button 在选中时使用透明背景绘制。

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_window_focused="false" android:state_enabled="true" android:drawable="@drawable/tranpsshape" />
<item android:state_window_focused="false" android:state_enabled="false" android:drawable="@drawable/tranpsshape" />
<item android:state_pressed="true" android:drawable="@drawable/pressedbuttonshape" />
<item android:state_focused="true" android:state_enabled="true" android:drawable="@drawable/selectedshape" />
<item android:state_enabled="true" android:drawable="@drawable/tranpsshape" />
<item android:state_focused="true" android:drawable="@drawable/tranpsshape" />
<item android:state_selected="true" android:drawable="@drawable/selectedshape" />
<item android:drawable="@drawable/tranpsshape" />
</selector>

selectedshape.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#A3DAF2"/>
</shape>

按下按钮形状.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#4ABDE8/>
</shape>

transpsshape.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#00000000"/>

</shape>

最佳答案

根据documentation

During each state change, the state list is traversed top to bottom and the first item that matches the current state will be used—the selection is not based on the "best match," but simply the first item that meets the minimum criteria of the state.

所以你需要把state_selected放在state_focused上面。所以你的文件看起来像这样

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_window_focused="false" android:state_enabled="true" android:drawable="@drawable/tranpsshape" />
<item android:state_window_focused="false" android:state_enabled="false" android:drawable="@drawable/tranpsshape" />
<item android:state_pressed="true" android:drawable="@drawable/pressedbuttonshape" />
<item android:state_selected="true" android:drawable="@drawable/selectedshape" />
<item android:state_focused="true" android:state_enabled="true" android:drawable="@drawable/selectedshape" />
<item android:state_enabled="true" android:drawable="@drawable/tranpsshape" />
<item android:state_focused="true" android:drawable="@drawable/tranpsshape" />
<item android:drawable="@drawable/tranpsshape" />
</selector>

关于Android:如何在选中时为按钮绘制不同的背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12320932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com