问题描述
|
我必须每30秒更改一次背景图片,但无法获得正确的结果
我已经尝试使用线程和TimerTask。但没有工作。
我有port1,port2 ... etc图片。
在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(),30000);
它不起作用,任何帮助将不胜感激。
谢谢
解决方法
用这个,行得通
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>
, 尝试这个:
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);
}
};
这是对的!