【问题标题】:Android Application - Police Siren SimulatorAndroid 应用程序 - 警笛模拟器
【发布时间】:2016-07-03 22:22:45
【问题描述】:

我想编写一个简单的应用程序,它会在指定的时间间隔内不断地将其颜色从红色变为蓝色,因此它可以模拟警笛。但我不知道如何编码,所以应用程序会改变它的颜色。

这是我试过的,当然不行……

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

【问题讨论】:

    标签: java android refresh siren


    【解决方案1】:

    试试这个,

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

    【讨论】:

      猜你喜欢
      • 2016-09-24
      • 2015-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-15
      • 2014-08-22
      相关资源
      最近更新 更多