前言
安卓的按壓效果的傳統(tǒng)方式是shape.xml文件卦尊,不過如果當(dāng)項(xiàng)目比較多按鈕都需要自定義按壓效果的話,shape.xml的數(shù)量可是非常頭疼的(即使是ctrl c+ ctrlv)腾窝,故此可以采用動(dòng)態(tài)方式進(jìn)行按壓效果的實(shí)現(xiàn)。
上代碼
/**
*
* @param RADIUS
* 角度
* @param normalFileName
* 正常顏色
* @param pressFileName
* 點(diǎn)擊顏色
* @param type
* -1:left 0:center 1:right 2:四角圓角
* @return
*/
public static StateListDrawable addDrawable(int RADIUS, int normalFileName,
int pressFileName, int type) {
StateListDrawable sd = new StateListDrawable();
if (RADIUS != 0) {
float[] float1 = null;
if (type == -1) {
float1 = new float[] { 0, 0, 0, 0, 0, 0, RADIUS, RADIUS };
} else if (type == 0) {
float1 = new float[] { 0, 0, 0, 0, 0, 0, 0, 0 };
} else if (type == 1) {
float1 = new float[] { 0, 0, 0, 0, RADIUS, RADIUS, 0, 0 };
} else if (type == 2) { // 設(shè)置四個(gè)角為圓角
float1 = new float[] { RADIUS, RADIUS, RADIUS, RADIUS, RADIUS,
RADIUS, RADIUS, RADIUS };
} else {
float1 = new float[] { 0, 0, 0, 0, RADIUS, RADIUS, RADIUS,
RADIUS };
}
GradientDrawable gd = new GradientDrawable();
gd.setCornerRadii(float1);
gd.setColor(normalFileName);
GradientDrawable gd2 = new GradientDrawable();
gd2.setCornerRadii(float1);
gd2.setColor(pressFileName);
int pressed = android.R.attr.state_pressed;
int window_focused = android.R.attr.state_window_focused;
int focused = android.R.attr.state_focused;
int selected = android.R.attr.state_selected;
sd.addState(new int[] { pressed, window_focused }, gd2);
sd.addState(new int[] { pressed, -focused }, gd2);
sd.addState(new int[] { selected }, gd2);
sd.addState(new int[] { focused }, gd2);
sd.addState(new int[] {}, gd);
return sd;
} else {
GradientDrawable gd = new GradientDrawable();
gd.setColor(normalFileName);
GradientDrawable gd2 = new GradientDrawable();
gd2.setColor(pressFileName);
int pressed = android.R.attr.state_pressed;
int window_focused = android.R.attr.state_window_focused;
int focused = android.R.attr.state_focused;
int selected = android.R.attr.state_selected;
sd.addState(new int[] { pressed, window_focused }, gd2);
sd.addState(new int[] { pressed, -focused }, gd2);
sd.addState(new int[] { selected }, gd2);
sd.addState(new int[] { focused }, gd2);
sd.addState(new int[] {}, gd);
return sd;
}
}
小結(jié)
小建議,建一個(gè)獲取不同按壓效果的管理類虹脯,這樣就可以統(tǒng)一入口替換資源圖片了驴娃。歡迎各位大神有更好的做法分享到評(píng)論區(qū)~