2015-09-27 98 views
0

如何制作在特定时间后自动在颜色之间更改的应用程序?我的代码由于某种原因不起作用在特定时间后更改颜色

Random r = new Random(); 
    Timer t = new Timer(); 
    LinearLayout ll = (LinearLayout) findViewById(R.id.ll); 

    long m = System.nanoTime(); 
    int seconds = (int) (m/1000); 

    if(seconds <= 5){ 
     ll.setBackgroundColor(Color.BLACK); 
    }else{ 
     ll.setBackgroundColor(Color.WHITE); 
    } 

例如,屏幕是黑色的,并在特定的时间后白色。而且时间越短,变化就越快。

+0

它显示的是什么颜色? –

+0

一直都是白色的 –

+0

你需要在'onTick()'方法的定时器中放置'if条件',最好使用'CountdownTimer'参见这里http://stackoverflow.com/questions/7483909/android-timer-ontick-问题 –

回答

1

您正在尝试将纳秒转换为秒,但实际上您所做的并不相同!

尝试

int seconds = (int) (m/1000000000); 

转换为nan0秒来秒

编辑:

,如果你只是想继续改变颜色使用此代码:

public static int color = 1; 
android.os.Handler customHandler = new android.os.Handler(); 
       customHandler.postDelayed(updateTimerThread, 0); 

和其定义:

private Runnable updateTimerThread = new Runnable() 
{ 
     public void run() 
     { 
      //write here whaterver you want to repeat 
      if(color == 1){ 
      ll.setBackgroundColor(Color.BLACK); 
      color = 2; 
      }else{ 
       ll.setBackgroundColor(Color.WHITE); 
       color = 1; 
      } 

      customHandler.postDelayed(this, 5000);// will repeat after 5 seconds 
     } 
}; 
+0

仍然一样。 –

+0

edited .. please try it ..你可能不需要任何循环迭代! –

0

尝试代码

Calendar c = Calendar.getInstance(); 
int seconds = c.get(Calendar.SECOND); 
//Adding Log Statement to check 

Log.i(Tag, String.valueOf(seconds); 
if(seconds % 10 < 5){ 
     ll.setBackgroundColor(Color.BLACK); 
    }else{ 
     ll.setBackgroundColor(Color.WHITE); 
    } 
+0

现在屏幕只有黑色。 –

+0

尝试登录以查看秒数值以更好地理解 – MDMalik

1

您可以使用胎面来管理此之后,试试这个。线程将是实现这一目标的最佳方式,因为您想要定期连续更改颜色。

Handler handler ; 
LinearLayout ll ; 
int i = 0; 
int colors[] = {Color.BLACK, Color.WHITE, Color.BLUE, Color.GREEN, Color.GRAY}; 
Runnable runnable = new Runnable() { 
    @Override 
    public void run() { 
     ll.setBackgroundColor(colors[i]); 
     i++; 
    } 
}; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    ...... 
    ....... 
    handler = new Handler(); 
    ll = (LinearLayout) findViewById(R.id.ll); 

    Thread myTread = new Thread(){ 
     public void run() { 
      try { 
       while(true){ 
        sleep(3000); 
        handler.post(runnable); 

       } 

      } 
      catch (InterruptedException e) {} 
     } 

    }; 
    myTread.start(); 
} 

代码将改变背景颜色每3secs sleep(3000)写在代码。也每次它改变它从一组预定义的颜色数组中选择。

你也可以使用随机生成的颜色。要么随机生成rgb值,要么可以将颜色存储在阵列中,因为我已经完成并随机迭代它。

3

请尝试以下代码以更改颜色。 使用倒数计时器用条件改变颜色。

new CountDownTimer(5000,1000) 
{ 
    onFinish() 
    { 

      if(flag==1) 
      { 
        //color set black 
        flag=0; 
        //start the countdown timer again. 
      } 
      else 
      { 
        //color set white 
        flag=1; 
        //start the countdown timer again. 
      } 
    } 
}