系统中默认的按钮被按下的颜色和未点击时的颜色不一样,该种实现可以用Java代码和XML实现。
Java代码实现(通过StateListDrawable)
okBtn.setBackgroundDrawable(addStateDrawable(this, R.drawable.btn_normal, R.drawable.btn_ selected, R.drawable.btn_selected));
cancelBtn.setBackgroundDrawable(addStateDrawable(this, R.drawable.btn_normal, R.drawable. btn_selected, R.drawable.btn_selected));
private StateListDrawable addStateDrawable(Context context, int idNormal, int idPressed, int idFocused) {
StateListDrawable sd = new StateListDrawable();
Drawable normal = idNormal == -1 ? null : context.getResources().getDrawable(idNormal)
Drawable press(略);Drawable focus(略);
//注意该处的顺序,只要有一个状态与之相配,背景就会被换掉
//所以不要把大范围放在前面了,如果sd.addState(new[]{},normal)放在第一个的话,就没有q 什么效果了
sd.addState(new int[]{android.R.attr.state_enabled, android.R.attr.state_focused}, focus);
sd.addState(new int[]{android.R.attr.state_pressed, android.R.attr.state_enabled}, pressed);
sd.addState(new int[]{android.R.attr.state_focused}, focus);
sd.addState(new int[]{android.R.attr.state_pressed}, pressed);
sd.addState(new int[]{android.R.attr.state_enabled}, normal);
sd.addState(new int[]{}, normal);
return sd;
}
xml方式实现时,可以先了解下对应xml的语法
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:constantSize=["true" | "false"]
android:dither=["true" | "false"]
android:variablePadding=["true" | "false"] >
<item
android:drawable="@[package:]drawable/drawable_resource"
android:state_pressed=["true" | "false"]
android:state_focused=["true" | "false"]
android:state_selected=["true" | "false"]
android:state_active=["true" | "false"]
android:state_checkable=["true" | "false"]
android:state_checked=["true" | "false"]
android:state_enabled=["true" | "false"]
android:state_window_focused=["true" | "false"] />
</selector>
转载于:https://blog.51cto.com/6169621/1617345