Android应用程序 - 警笛模拟器

时间:2016-03-17 14:00:01

标签: java android refresh siren

我想写一个简单的应用程序,它会在指定的时间间隔内从红色到蓝色连续变化,因此它会模拟警笛。但我不知道代码如何,因此应用程序将改变它的颜色。

这是我尝试过的,当然它无法正常工作......

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 个答案:

答案 0 :(得分:0)

试试这个,

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);


    }
}
相关问题