Reputation: 181
I have a button with the background. I need that when you click on it, the background changed, and when I release it, the background is the same.
@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;
}
when I write this code, the background changes once and always in a state of becoming "pressed"
Upvotes: 0
Views: 127
Reputation: 9141
create xml into 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>
Now set this xml to button background property.
Upvotes: 8
Reputation: 9700
@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;
}
}
Upvotes: 2