我想随机化将从数据库中提取的背面图像(代码仍未添加),但我写的代码不起作用。我原本刚刚添加了翻转功能。我搜索了如何随机化图像并尝试按照给出的代码。可悲的是,它不适合我。
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);
}
答案 0 :(得分:0)
代码中的两件事对我来说很突出:
ImageView imgView = new ImageView(this);
此ImageView不是视图层次结构的一部分,这意味着它不在屏幕上。屏幕上有没有意味着什么?如果没有,那么我认为你不需要这个。
public void showUpperLeftImage(View v){
imgView.setImageResource(id);
}
您有四种方法可以更改不在屏幕上的视图图像。根据他们的方法名称来判断,我想您想要使用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);
}