Android Application - Police Siren Simulator

315 Views Asked by At

I would like to write simple application that changes continiously it's color from red to blue at specified intervals of time, so it simulates police siren. But I don't know how code so the application will be changing it's color.

here's what I've tried, of course it can't work...

LinearLayout mainBackground;
String currentColor = "Blue";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mainBackground = (LinearLayout) findViewById(R.id.mainBackgroundID);
    while(true) {
        sleep(250);
        if (currentColor.equals("Blue")) {
            currentColor = "Red";
            mainBackground.setBackgroundColor(0xFFFF0000);
        } else {
            currentColor = "Blue";
            mainBackground.setBackgroundColor(0xFF0008FF);
        }
    }
}
1

There are 1 best solutions below

0
On

Try this,

public class MainActivity extends AppCompatActivity {

    LinearLayout llParent;
    int currentColor = Color.BLUE;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        llParent = (LinearLayout) findViewById(R.id.llParent);
        llParent.setBackgroundColor(currentColor);
        final Handler handler = new Handler();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (currentColor == Color.BLUE) {
                    currentColor = Color.RED;
                } else {
                    currentColor = Color.BLUE;
                }
                llParent.setBackgroundColor(currentColor);
                handler.postDelayed(this, 1000);
            }
        };
        handler.post(runnable);


    }
}