0
我試圖製作一個按鈕,點擊它時會從一組卡中選取一張隨機卡並將其顯示到ImageView中。 要做到這一點,我有一個卡類他們的價值和他們的ID(圖像卡名稱繪製)。setImageResource導致應用程序崩潰
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到製表[],當按鈕平局點擊它挑選從標籤[]一個隨機的,我嘗試再改變我的ImageView與採摘卡的圖像獲取卡的ID和使用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);
}
});
}
}
這工作完美,我編輯此文件試圖正確使用setImageResource和完成忘記了我爲靜態編輯。對於構造函數來說,這是我的一個基本錯誤,我的錯誤。非常感謝 ! – Rhohen
@Rhohen沒問題。不要忘記接受答案。 –