Reputation: 55
I would like to set image1 for the button, but when it is pressed - change it to image2. After releasing, the button should be again an image1. I tried to do it this way in onClick() method:
button.setImageResource(R.drawable.image1);
if(button.isPressed())
button.setImageResource(R.drawable.image2);
but after first pressing the image of button changed to the image2 and stayed like that.
Could You help me with that problem?
Upvotes: 0
Views: 1530
Reputation: 38585
You can do this easily with a state list drawable, and it requires no additional java code on your part (unless you are creating a StateListDrawable
at runtime, but even that is a more suitable approach than implementing custom touch interaction).
Upvotes: 2
Reputation: 12953
I think this is what you want:
MyCustomTouchListener myCustomTouchListener = new MyCustomTouchListener();
button.setOnTouchListener(myCustomTouchListener);
Now the MyCustomTouchListener :
class MyCustomTouchListener implement OnTouchListener {
public boolean onTouch(View v, MotionEvent event)
{
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
// touch down code
button.setImageResource(R.drawable.image1);
break;
case MotionEvent.ACTION_MOVE:
// touch move code
break;
case MotionEvent.ACTION_UP:
// touch up code
button.setImageResource(R.drawable.image1);
break;
}
return true;
}
}
Upvotes: 2
Reputation: 479
Use the following:
int dispImg = 0;
button.setImageResource(R.drawable.image1);
if (button.isPress()) {
if (dispImg == 0) {
button.setImageResource(R.drawable.image2);
dispImg = 1;
}
else if (dispImg == 1) {
button.setImageResource(R.drawable.image1);
dispImg = 0;
}
}
Explanation: dispImg keeps track of the image you're showing. When it is 0, it means that the 1st Image is showing and so, we should switch to the 2nd.
Hope I Helped :D
Upvotes: 0