2011-05-28 153 views
1

更改背景我有每30秒更换背景图片,但我没有得到正确的结果在特定的时间间隔

我试图与线程和TimerTask。但没有工作。 我有port1,port2 ...等图像。

在TimerTask背景消失了。

class Task1 extends TimerTask { 
    public void run() { 
     System.out.println("Checking a"); 
     Random r = new Random(); 
     int i = r.nextInt(3) + 1; 
     rl.setBackgroundResource(getResources().getIdentifier(
        "port" + i, "drawable","com.samcom.breakingdowncd")); 

    } 
} 

Timer timerBackground = new Timer(); 
timerBackground.scheduleAtFixedRate(new Task1(), 0, 30000); 

它不工作,任何帮助将不胜感激。 感谢

回答

3

利用这一点,它的工作原理

private static final long GET_DATA_INTERVAL = 1000; 
    int images[] = {R.drawable.cloud1,R.drawable.cloud2}; 
    int index = 0; 
    ImageView img; 
    Handler hand = new Handler(); 

    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     this.setContentView(R.layout.main); 
     img = (ImageView) findViewById(R.id.image); 
     hand.postDelayed(run, GET_DATA_INTERVAL); 
    } 

    Runnable run = new Runnable() { 
     @Override 
     public void run() { 
      img.setBackgroundDrawable(getResources().getDrawable(images[index++])); 
      if (index == images.length) 
       index = 0; 
      hand.postDelayed(run, GET_DATA_INTERVAL); 
     } 
    }; 

XML代码:

<?xml version="1.0" encoding="UTF-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:id="@+id/line"> 
    <ImageView 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:id="@+id/image" 
    /> 
</LinearLayout> 
+0

没有用吗? – George 2011-05-29 12:56:30

+0

是的,谢谢你的帮助。它的工作 – djk 2011-05-30 11:45:01

+0

不错的教程.....真棒 – 2011-10-19 04:26:25

0

试试这个:

Runnable run = new Runnable() { 
@Override 
public void run() { 
if (index < images.length){ 
    img.setBackgroundDrawable(getResources().getDrawable(images[index++]));} 
else{ 
    index = 0; 
    } 
    hand.postDelayed(run, GET_DATA_INTERVAL); 
    } 
    }; 

这是正确的!