[英]I can not change the background of the button when pressed
我有一個帶有背景的按鈕。 我需要當您單擊它時,背景會改變,而當我釋放它時,背景是相同的。
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (v.getId()){
case R.id.button:
if (v.isEnabled()){
btn.setBackgroundResource(R.drawable.btn_pressed);
}else if (!v.isEnabled()){
btn.setBackgroundResource(R.drawable.btn_normal);
}
break;
}
return false;
}
當我編寫此代碼時,背景發生一次更改,並且始終處於“被按下”狀態
將xml創建為drawable。
button_effect.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" android:drawable="@drawable/button_green_dark"></item>
<item android:drawable="@drawable/button_green"></item>
</selector>
現在將此xml設置為button背景屬性。
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
btn.setBackgroundResource(R.drawable.btn_pressed);
break;
case MotionEvent.ACTION_UP:
btn.setBackgroundResource(R.drawable.btn_normal);
break;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.