我创建了一个按钮,每次单击它时都会显示一个随机图像。然而: - 显示图像非常慢 - 有时,我必须在按钮上单击2次才能显示新的随机图像
为什么?
然后,我在我的drawable中添加了更多图像,现在应用程序在显示2张图像后崩溃...
为什么?
这是java代码 - 希望一切都清楚,你可以帮我一把
public class nextActivity扩展Activity {
int[] cards = {R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5,
...
R.drawable.image32,
R.drawable.image33};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
// initializing the image view
ImageView m_imgRandom = (ImageView) findViewById(R.id.imgRandom);
// choosing a random number from 0 to 33
int n = new Random().nextInt(33);
// choosing the random image from cards array using the random number
m_imgRandom.setImageResource(cards[n]);
Button myButtonRoll = (Button) findViewById(R.id.buttonRoll);
myButtonRoll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("openclass", "yay it works!");
ImageView myRollAgain = (ImageView) findViewById(R.id.imgRandom);
// choosing a random number from 0 to 33
int n = new Random().nextInt(33);
// choosing the random image from cards array using the random number
myRollAgain.setImageResource(cards[n]);
}
});
}
}`
答案 0 :(得分:0)
ImageView m_imgRandom = (ImageView) findViewById(R.id.imgRandom);
ImageView myRollAgain = (ImageView) findViewById(R.id.imgRandom);
你注入相同的视图两次,你已经将它注入m_imgRandom,你的onCLick内部不再注入它,只需使用相同的:
m_imgRandom.setImageResource(cards[n]);
当然,如果是另一个imageView给它另一个id。