gpt4 book ai didi

java - 如何在 android studio 中随机化图像?我写的代码不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 13:28:14 27 4
gpt4 key购买 nike

我想随机化从数据库中获取的背面图像(代码仍未添加),但我编写的代码不起作用。我本来只是添加了翻转功能。我搜索了如何随机化图像并尝试遵循给出的代码。遗憾的是它不适合我。

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// get references to the imageView objects
imgUpperLeft = (ImageView) findViewById(R.id.imgUpperLeft);
imgUpperRight = (ImageView) findViewById(R.id.imageView2);
imgLowerLeft = (ImageView) findViewById(R.id.imageView3);
imgLowerRight = (ImageView) findViewById(R.id.imageView4);

// Setting the initial image (First face of cards)
imgUpperLeft.setImageResource(R.drawable.img_waterfall);
imgUpperRight.setImageResource(R.drawable.img_waterfall);
imgLowerLeft.setImageResource(R.drawable.img_waterfall);
imgLowerRight.setImageResource(R.drawable.img_waterfall);

imgUpperLeft.setVisibility(View.VISIBLE);
imgUpperRight.setVisibility(View.VISIBLE);
imgLowerLeft.setVisibility(View.VISIBLE);
imgLowerRight.setVisibility(View.VISIBLE);


}


ImageView imgView = new ImageView(this);
Random rand = new Random();
int rndInt = rand.nextInt(4) + 1; // n = the number of images, that start at idx 1
String imgName = "img" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());

// Shows the second face of the cards

public void showUpperLeftImage(View v){
imgView.setImageResource(id);
}
public void showUpperRightImage(View v){
imgView.setImageResource(id);
}
public void showLowerLeftImage(View v){

imgView.setImageResource(id);
}
public void showLowerRightImage(View v){
imgView.setImageResource(id);
}

最佳答案

您的代码中的两件事对我来说很突出:

ImageView imgView = new ImageView(this);

此 ImageView 不是 View 层次结构的一部分,这意味着它不在屏幕上。它本来就应该出现在屏幕上吗?如果没有,那么我认为您不需要这个。

public void showUpperLeftImage(View v){
imgView.setImageResource(id);
}

您有四种与此类似的方法可以更改不在屏幕上的 View 的图像。从它们的方法名称来看,我认为您想要更改之前使用 findViewById() 找到的四个 ImageView 的图像。

我想你想这样做:

public void showUpperLeftImage(int id) {
imgUpperLeft.setImageResource(id);
}
public void showUpperRightImage(int id) {
imgUpperRight.setImageResource(id);
}
public void showLowerLeftImage(int id) {
imgLowerLeft.setImageResource(id);
}
public void showLowerRightImage(int id) {
imgLowerRight.setImageResource(id);
}

关于java - 如何在 android studio 中随机化图像?我写的代码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32444145/

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