gpt4 book ai didi

android - Android中的随机图像?

转载 作者:行者123 更新时间:2023-11-30 04:41:48 25 4
gpt4 key购买 nike

我正在尝试使用随机图像制作 View 。我有代码并且没有错误,但是当我单击按钮转到随机图像时,它只是保持不变。

我的来源是:

private static final Random rgenerator = new Random();

private static final Integer[] mImageIds =
{ R.drawable.img2, R.drawable.img1, R.drawable.img3, };

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Integer q = mImageIds[rgenerator.nextInt(mImageIds.length)];
ImageView iv = (ImageView) findViewById(R.id.imageviewyeah);
iv.setTag(q);

View nextButton = findViewById(R.id.next_image_button);
nextButton.setOnClickListener(this);
}

public void onClick(View v)
{
switch (v.getId())
{
case R.id.next_image_button:
Intent i = new Intent(this, RandomImage.class);
startActivity(i);
break;
}
}

最佳答案

只需保留对您的 ImageView 的引用,并使用随机资源之一调用 setImageResource(int id)。您无需启动新的 Activity 即可检索随机资源 ID...

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Integer q = mImageIds[rgenerator.nextInt(mImageIds.length)];
final ImageView iv = (ImageView) findViewById(R.id.imageviewyeah);

View nextButton = findViewById(R.id.next_image_button);
nextButton.setOnClickListener(new OnClickListener() {
public void onClick(View V) {
int resource = mImageIds[rgenerator.nextInt(mImageIds.length)];
iv.setImageResource(resource);
}
});
}

关于android - Android中的随机图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5861387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com