Button Background Selector

余生长醉 提交于 2019-12-30 18:39:31

问题


I try to switch the background of Buttons if they are pressed. I build a Selector like the answer suggested here: Standard Android Button with a different color

finally I want to put GradientDrawables inside, but for debug purposes I only want to set a color, to see it is working. Here is my Selector

<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">

  <item android:drawable="@color/red"/>
  <item 
    android:state_focused="true"
    android:drawable="@color/white"/>
   <item 
    android:state_pressed="true"
    android:drawable="@color/white"/>
</selector>

unfortunatly this doesn't work. I set the Selector as Background from my Button, and only see them in red color. What Am I doing wrong (Build Target 2.1)


回答1:


put this at the end

item android:drawable="@color/red"

i mean as the third option, it will work. android checks the xml conditions from the start, the first tag doesn't have any condition, so it will always pick red, so you have put conditions first and then the default one.




回答2:


here is the code I use, and it works really well.

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

    <item android:drawable="@drawable/button" android:state_enabled="true" />
    </selector>

here I use two images I made using photoshop as a background

the first is button_clicked and the second is button

copy it and change use your own resources.

hope I could help :)



来源:https://stackoverflow.com/questions/7335345/button-background-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!