Change Background at specific interval
I have to change background image at every 30 seconds but i am not getting proper result
I have tried with thread and TimerTask. but no wor开发者_高级运维k. I have port1, port2...etc images.
In TimerTask background is gone.
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);
Its not working, any help will be appreciated. Thanks
use this, it works
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 Code:
<?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>
Try this:
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);
}
};
This is correct!
精彩评论