Please, suggest me some good practice to change button background color onclick(for few seconds). I use Android API 22.
Asked
Active
Viewed 1,264 times
-4
-
1What did you try so far? Please post any related code. – cygery Jul 12 '15 at 12:10
-
I ask for help to find out which style control responsible for such things, so I didn't try any code. If you now place in Android style guide where I can find an answer, please point me. – Rudziankoŭ Jul 12 '15 at 12:15
-
How about http://developer.android.com/reference/android/view/View.html#setBackgroundResource(int) – ci_ Jul 12 '15 at 12:19
-
1Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it. – runDOSrun Jul 12 '15 at 12:21
2 Answers
2
I had a similar issue a few days back, so feel free to use my code.
Button myButton; //as a "global" variable so that it is also recognized in the onClick event.
myButton = (Button) findViewById(R.id.b)
myButton.setBackgroundColor(Color.BLACK); //set the color to black
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myButton.setBackgroundColor(Color.RED); //set the color to red
// Delay of 2 seconds (200 ms) before changing back the color to black
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
myButton.setBackgroundColor(Color.BLACK); //set the color to black
}
}, 200);
}
}
I don't know if this is considered good practice though...
Have a nice day!
0
I come up with this solution for Android API 21:
@Override
public void onClick(final View view) {
final int redColor = 0xFFFF0000;
view.getBackground().setColorFilter(redColor, PorterDuff.Mode.MULTIPLY);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
view.getBackground().clearColorFilter();
}
}, 700);
}

Rudziankoŭ
- 10,681
- 20
- 92
- 192