Android开发问题,我要在XML中的固定位置显示图片,图片有很多张,我要随机展示,如何操作,求详细代码。

2024-12-22 19:26:35
推荐回答(1个)
回答1:

private ImageView imageView;
private Button button;
private int i, a;
private Integer[] integers = new Integer[] { R.drawable.android1,
R.drawable.android2, R.drawable.android3, R.drawable.android4,
R.drawable.android5, R.drawable.android6, R.drawable.android7,
R.drawable.android8 };
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) findViewById(R.id.image);
button = (Button) findViewById(R.id.random);
imageView.setBackgroundResource(integers[0]);
// 1 通过点击事件来随机显示
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
a = (int) (Math.random() * 8);
System.out.println(a);
imageView.setBackgroundResource(integers[a]);
}
});
// 2 通过线程来随机显示
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (i < 5) {
i++;
handler.sendEmptyMessage(0);
try {
Thread.sleep(5000);
if (i == 5)
i = 0;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
// for (i = 0; i < 2; i++) {
// a = (int) (Math.random() * 8);
// System.out.println(a);
// handler.sendEmptyMessage(0);
// try {
// Thread.sleep(3000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// if (i > 0) {
// i = 0;
// }
// }
}
Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
a = (int) (Math.random() * 8);
imageView.setBackgroundResource(integers[a]);
break;
default:
break;
}
};
};
自己随便写的。不清楚的话, 你再问。