我试图制作一个按钮,当点击它时从一组卡中挑选一张随机卡并将其显示到ImageView中。 要做到这一点,我有一个Card类的值和他们的id(可绘制的图像卡名称)。
public class Carte {
int valeur;
static String nomCarte;
public Carte(int valeur, String nomImage) {
valeur = this.valeur;
nomCarte = this.nomCarte;
}
public static String getImageId() {
return nomCarte;
}
}
我将其中的52个初始化为tab [],当点击按钮绘制时,它从tab []中选择一个随机的,然后我尝试通过获取ID的ID来更改我的ImageView卡被选中并使用setImageResource但是它会让我的应用程序崩溃你能帮我吗?
这是我的mainActivity代码:
public class MainActivity extends AppCompatActivity {
protected Carte tab[];
protected ImageView imageCarte;
protected Button afficherCarte;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageCarte = (ImageView) findViewById(R.id.imageCarte);
tab = new Carte[]{new Carte(1, "c_1"), new Carte(1, "d_1"), new Carte(1, "h_1"), new Carte(1, "s_1"),
new Carte(2, "c_2"), new Carte(2, "d_2"), new Carte(2, "h_2"), new Carte(2, "s_2"),
new Carte(3, "c_2"), new Carte(3, "d_3"), new Carte(3, "h_3"), new Carte(3, "s_3"),
new Carte(4, "c_4"), new Carte(4, "d_4"), new Carte(4, "h_4"), new Carte(4, "s_4"),
new Carte(5, "c_5"), new Carte(5, "d_5"), new Carte(5, "h_5"), new Carte(5, "s_5"),
new Carte(6, "c_6"), new Carte(6, "d_6"), new Carte(6, "h_6"), new Carte(6, "s_6"),
new Carte(7, "c_7"), new Carte(7, "d_7"), new Carte(7, "h_7"), new Carte(7, "s_7"),
new Carte(8, "c_8"), new Carte(8, "d_8"), new Carte(8, "h_8"), new Carte(8, "s_8"),
new Carte(9, "c_9"), new Carte(9, "d_9"), new Carte(9, "h_9"), new Carte(9, "s_9"),
new Carte(10, "c_10"), new Carte(10, "d_10"), new Carte(10, "h_10"), new Carte(10, "s_10"),
new Carte(11, "c_11"), new Carte(11, "d_11"), new Carte(11, "h_11"), new Carte(11, "s_11"),
new Carte(12, "c_12"), new Carte(12, "d_12"), new Carte(12, "h_12"), new Carte(12, "s_12"),
new Carte(13, "c_13"), new Carte(13, "d_13"), new Carte(13, "h_13"), new Carte(13, "s_13"),};
afficherCarte = (Button) findViewById(R.id.afficherCarte);
afficherCarte.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Random r = new Random();
int i1 = r.nextInt(53 - 1) + 1;
int id = getResources().getIdentifier(tab[i1].getImageId(), "drawable", getPackageName());
imageCarte.setImageResource(id);
}
});
}
}
答案 0 :(得分:0)
您的构造函数是错误的,并且您在imageId上创建了一个静态字段,如果不删除它,它将始终是相同的ID。
public Carte(int valeur, String nomImage) {
valeur = this.valeur;
nomCarte = this.nomCarte;
}
您永远不会将方法参数存储到类字段中。 你必须反过来使用它,如
this.valeur = valeur;
this.nomCarte = nomCarte;
因此,你的getter会返回null
。除此之外,删除静态修饰符
public String getImageId() {
return nomCarte;
}