-1

I've placed this code on my onClickListener:

btnListenC.setBackgroundResource(R.drawable.lisbtnpressed);

But from here, how do I make it so that the drawable 'lisbtnpressed' changes back to its original image after a few seconds please?

TN888
  • 7,659
  • 9
  • 48
  • 84
Fuchsia
  • 77
  • 1
  • 7

2 Answers2

2

You can do it easier with an XML file in your drawable folder (mybutton.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/mydrawable />
   <item android:state_focused="true" android:drawable="@drawable/otherdrawable" />
   <item android:drawable="@color/redcolor" />
</selector>

and use this in button xml code

android:background:@drawable/mybutton

As you can see in the first piece of code you can have a different drawable (color, image...) for each button state. The button states can be found here or here.

With this approach you don't need to use any code.

Merlevede
  • 8,140
  • 1
  • 24
  • 39
  • Thanks! What's item android:drawable="@color/redcolor" for? Do I need to indicate a color of some kind or something? – Fuchsia Feb 19 '14 at 17:49
  • @Fuchsia that is the resource you refer in `colors.xml`. – Raghunandan Feb 19 '14 at 17:53
  • @Fuchsia Drawable can be an image or a color. That last item is just an example, but as you can see it has no 'state' attribute, meaning that's the default drawable. – Merlevede Feb 19 '14 at 17:53
0

Use a selector

android button selector

or use OnTouchListener on ACTION_DOWN change to lisbtnpressed on ACTION_UP set to default

 btnListenC.setOnTouchListener(new OnTouchListener() {
 @Override
 public boolean onTouch(View v, MotionEvent event) {
 switch(event.getAction())
 {
   case MotionEvent.ACTION_DOWN :
                  // change
             btnListenC.setBackgroundResource(R.drawable.lisbtnpressed);
   break;
   case MotionEvent.ACTION_UP :
                 // set to original
             btnListenC.setBackgroundResource(R.drawable.lisbtnoriginal);   
   break; 
    }
 return true;
   }
 });
Community
  • 1
  • 1
Raghunandan
  • 132,755
  • 26
  • 225
  • 256