1

我必须每 30 秒更改一次背景图像,但我没有得到正确的结果

我尝试过使用线程和 TimerTask。但没有工作。我有端口 1、端口 2...等图像。

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

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

4

2 回答 2

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>
于 2011-05-28T07:18:20.297 回答
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);
   }
  };

这是对的!

于 2013-10-24T10:26:50.557 回答