gradual button color change on android
android, background-color, button
Solution
I solved this problem using TransitionDrawable. You can follow next step:
- Create an xml file in the drawable folder, and write there something like:
`
<?xml version="1.0" encoding="UTF-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/color1" />
<item android:drawable="@color/color2" />
</transition>
`
- Then, in your xml for this button (or another element / View) you should reference this TransitionDrawable in the `android:background` attribute.
- Also you should have colors stored as resources: for this, you have to create an xml like following:
`
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<color name="color1">#990000</color>
<color name="color2">#cc3311</color>
</resources>
`
and save this xml file in the /res/values/ folder, name the xml as color.xml.
- And initiate the transition in code:
`
int durationMillis = 2000;
TransitionDrawable transition = (TransitionDrawable) changeColorBtn.getBackground();
transition.startTransition(durationMillis);
`
This is helped me, I hope it will be useful for others.
Problem
I want gradually change button color, after click on it. I mean, button must have, for example next set of colors: by default - dark dark blue, then dark blue, then blue, then light blue, and in the end - the lightest blue. This is only example, really I want to change button color in cycle, like in the next code. But, I can't understand, why it doesn't show intermediate colors. It shows only first color, and the last one. How to improve this? ``` public class ActivityExample extends Activity { private changeColorBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_animations); changeColorBtn = (Button) findViewById(R.id.btn_change_color); changeColorBtn.setBackgroundColor(Color.BLACK); changeColorBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { changeButtonColor(v); } }); } private void changeButtonColor(View v) { // How many intermediate color will be, and delay in millisecond between them int count = 20, delay = 100; for (int i = 0; i < count; i++) { try { int color = ((ColorDrawable) changeColorBtn.getBackground()) .getColor(); int blue = Color.blue(color), red = Color.red(color), green = Color.green(color); changeColorBtn.setBackgroundColor(Color.rgb(red+10, green+5, blue+3)); Thread.sleep(delay); } catch (InterruptedException inE) { } } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } ``` }