我想改变一个按钮的背景,当它被点击。我尝试使用选择器。但是没有成功。下面是选择器(add_grp_slctrr .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="@drawable/add_grp_d"/>
<item android:state_pressed="true" android:drawable="@drawable/add_grp_d" />
<item android:drawable="@drawable/add_grp" />
</selector>
和按钮:
<Button
android:id="@+id/addGrpBtn"
android:layout_width="55dp"
android:layout_height="45dp"
android:layout_gravity="center"
android:background="@drawable/add_grp_slctr"
android:onClick="addGrpDialogOpen" />
add_grp_d和add_grp为图片(png)
我尝试了一个类似的代码,默认为白色,当按下按钮时为黑色:
//***这是要在可绘制文件夹中声明的btn_selector ***
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="@android:color/black" /> <!-- pressed -->
<item android:drawable="@android:color/white" /> <!-- default -->
</selector>
并在button.xml中调用它-->
android:background="@drawable/btn_selector"
希望这对你有帮助…:)
浏览http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList一次。此外,state_focussed for button仅在使用硬件键盘对焦按钮时有效。至于你的情况
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="false" android:state_selected="false" android:drawable="@drawable/button_default"/>
<item android:state_pressed="true" android:state_selected="false" android:drawable="@drawable/button_default" />
<item android:state_pressed="false" android:state_selected="true" android:drawable="@drawable/button_selected"/>
<item android:state_pressed="true" android:state_selected="true" android:drawable="@drawable/button_selected" />
<item android:drawable="@drawable/button_selected" />
</selector>
使用选择器
像这样修改你的代码
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_focused="true" android:drawable="@drawable/add_grp_d"/>
<item android:state_pressed="true" android:drawable="@drawable/add_grp" />
<item android:drawable="@drawable/add_grp_d" />
</selector>
我的代码
<item android:drawable="@drawable/shadow_design_click" android:state_pressed="true"/>
<item android:drawable="@drawable/shadow_design" android:state_focused="true"/>
<item android:drawable="@drawable/shadow_design"/>
</selector>
我认为你应该稍微改变一下选择器。
不传递定制XML文件,如果您只是想更改按钮的颜色,那么您可以尝试以下方法:
Button lineColorCode = (Button)findViewById(R.id.button1);
现在在按钮的点击事件中使用以下代码:
int color = Color.parseColor("#AE6118"); //The color u want
lineColorCode.setColorFilter(color);