xml代码:
color.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="btn_normal">#88FE9D3D</color>
<color name="btn_pressed">#EEFE9D3D</color>
</resources>
selector_btn.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/btn_pressed" android:state_pressed="true"/>
<item android:drawable="@color/btn_normal" android:state_pressed="false"/>
</selector>
java中调用:
TextView tvXML = (TextView) findViewById(R.id.tvXML);
tvXML.setClickable(true);
tvXML.setBackgroundDrawable(getResources().getDrawable(R.drawable.selector_btn));
java代码:
/** 获取一个selector */
public Drawable getSelectorDrawable() {
ColorDrawable cdNormal = new ColorDrawable(Color.parseColor("#88FE9D3D"));
ColorDrawable cdPressed = new ColorDrawable(Color.parseColor("#EEFE9D3D"));
StateListDrawable sld = new StateListDrawable();
sld.addState(new int[] { -android.R.attr.state_pressed }, cdNormal);
sld.addState(new int[] { android.R.attr.state_pressed }, cdPressed);
return sld;
}
java中调用:
TextView tvJAVA = (TextView) findViewById(R.id.tvJAVA);
tvJAVA.setClickable(true);
tvJAVA.setBackgroundDrawable(getSelectorDrawable());
StateListDrawable:http://developer.android.com/reference/android/graphics/drawable/StateListDrawable.html
State List:http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList