我写的代码可以每 3 秒更改一次背景,但不幸的是它只更改了 1 次,我尝试使用计数但它不起作用,哪里出错了?
public class MainActivity extends AppCompatActivity {
public static int count=0;
int images[] = new int[] {R.drawable.main, R.drawable.main2, R.drawable.main3, R.drawable.main4};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Handler().postDelayed(new Runnable() {
public void run() {
if (count < images.length) {
RelativeLayout background = (RelativeLayout) findViewById(R.id.activity_main);
Random rand = new Random();
int index = rand.nextInt(images.length);
background.setBackgroundResource(images[index]);
count++;
}
else{
count = 0;
}
}
}, 3000);
}
};
最佳答案
只需在 run() 方法中调用 handler.postDelayed 再次启动它,然后修改您的代码如下:
public class MainActivity extends AppCompatActivity {
int images[] = new int[] {R.drawable.main, R.drawable.main2, R.drawable.main3, R.drawable.main4};
final Handler animHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout background = (RelativeLayout) findViewById(R.id.activity_main);
animHandler.post(new Runnable() {
@Override
public void run() {
Random rand = new Random();
int index = rand.nextInt(images.length);
background.setBackgroundResource(images[index]);
animHandler.postDelayed(this, 3000);
}
});
}
};
}
关于android - 如何不停地更换背景图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45521265/