Maven Maverick Maven Maverick - 3 months ago 9
Android Question

Android - Dynamically changing background color of a layout

I want to change the background color of the

coordinatorLayout
every second.

But, what I find is that, the color
coordinatorLayout
changes from the initial color
RED
to directly the last color i.e.
#09FF00
in the
COLORS
array. The intermediate color don't show up in the layout, though they get logged in the
LogCat
.

What am I doing wrong ?

public class ColorActivity extends AppCompatActivity {

private static String COLORS [] = {"#FF0000", "#0000FF", "#09FF00"};

@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detect);

final CoordinatorLayout coordinatorLayout = (CoordinatorLayout) findViewById(R.id.fullscreenview);
coordinatorLayout.setBackgroundColor(Color.RED);

new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
}catch (Exception e) {
e.printStackTrace();
}
changeColor(coordinatorLayout);
}
}).start();

}

private void changeColor(final CoordinatorLayout coordinatorLayout) {
runOnUiThread(new Runnable() {
@Override
public void run() {
for (String color: COLORS) {
Log.i("COLOR", color);
coordinatorLayout.setBackgroundColor(Color.parseColor(color));
}
}
});
}

}

Answer

The transition is happening way to fast. In your run method you iterate over the colors which is way too fast for the human eye to perceive it.

Instead you'll probably want to put the loop iteration over the colors inside your Runnable, like this (which will pause at every color for one second):

new Thread(new Runnable() {
    @Override
    public void run() {
        for (final String color: COLORS) {
            Log.i("COLOR", color);
            changeColor(coordinatorLayout, color);
            try {
                Thread.sleep(1000);
            } catch (Exception e) {/* ... */}
        }
    }
}).start();

And then change your changeColor method to this:

private void changeColor(final CoordinatorLayout coordinatorLayout, final String color) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            coordinatorLayout.setBackgroundColor(Color.parseColor(color));
        }
    });
}
Comments