Craig Turner Craig Turner - 22 days ago 8
Android Question

Make android screen change color once per second

I am a beginner to android, with some java under my belt. I have completed the make my first app tutorial only.

Next I want to make an app to use simple 2D graphics

To start, I want to find a way of flashing the screen between two colors (red and green) in an infinite loop

wait int seconds;
make screen red;
wait int seconds;
make screen green;

loop forever;


Could anyone please point me to a tutorial(s) or source code(s) that may help?

Many Thanks

Answer Source

Thanks for the input, This code seems to work OK

package biz.consett.mydraw;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;

/* Flash the screen between red and green each second */
public class MainActivity extends Activity {
    final static int INTERVAL = 1000; // 1000=1sec   
    private static View myView = null;
    boolean whichColor = true;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myView = (View) findViewById(R.id.my_view);
        myView.setBackgroundColor(Color.RED);// set initial colour
        new Thread(new Runnable() {
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(INTERVAL);
                    } 
                    catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    updateColor();
                    whichColor = !whichColor;
                }
            }
        }).start();
    }

    private void updateColor() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (whichColor) 
                    myView.setBackgroundColor(Color.RED);
                else 
                    myView.setBackgroundColor(Color.GREEN);
            }
        });
    }
}

Layout, activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<View

android:id="@+id/my_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

</View>

</RelativeLayout>