Reputation: 2187
I want to change the button background color for a short period of time after the button is pressed. The button should regain it's previous condition after that period. Probably a handler is the correct decision for this problem, unfortunately i didn't found a working example for doing a similar thing. If anyone can give me a short example of how doing a such thing i would appreciate it.
Upvotes: 1
Views: 1326
Reputation: 93842
Do this :
public class LaunchActivity extends Activity implements OnTouchListener{
private Button yourButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
yourButton= (Button)findViewById(R.id.yourButton);
yourButton.setOnTouchListener(this);
}
@Override
public boolean onTouch(final View view, MotionEvent event) {
final int action = event.getAction();
if(view.getId()==R.id.yourButton){
if(action == MotionEvent.ACTION_DOWN)
yourButton.setBackgroundResource(R.drawable.ic_button_pressed);
if(action == MotionEvent.ACTION_UP){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
yourButton.setBackgroundResource(R.drawable.ic_button_normal);
}
}, 2000);
}
}
} }
Or with an onClick listener :
@Override
public void onClick(View v) {
yourButton.setBackgroundResource(R.drawable.first_icon);
// SLEEP 2 SECONDS HERE ...
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
yourButton.setBackgroundResource(R.drawable.second_icon);
}
}, 2000);
}
Upvotes: 3
Reputation: 6849
you can define an XML background for your button under res/drawable/button_background
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_background_pressed" android:state_pressed="true" />
<item android:drawable="@drawable/button_background_notpressed"/>
</selector>
and for use an ImageButton
<ImageButton
...
android:background="@drawable/button_background"
... />
Upvotes: 1