2016-03-17 135 views
-1

我想編寫簡單的應用,改變continiously它的顏色從紅到藍在時間指定的時間間隔,所以它模擬警笛。但我不知道代碼如何使應用程序改變它的顏色。Android應用程序 - 警笛模擬器

這裏就是我試過,當然它不能工作...

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

回答

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


    } 
} 
+0

作品,謝謝! ; ) – Hoymm

相關問題