Android 在ImageButton上动态设置图像

Android 在ImageButton上动态设置图像,android,Android,我环顾四周,但没有找到我的问题的答案。我有一个imageButton,想在按下按钮时更改图像。我正试图找到一种让Eclipse逐字解释代码的方法 String card = nextcard.toString(); //Becomes "Ace_Of_Hearts", for example theImageButton.setImageResource(R.drawable.card); //R.drawable.Ace_Of_Hearts is an image in the corr

我环顾四周,但没有找到我的问题的答案。我有一个imageButton,想在按下按钮时更改图像。我正试图找到一种让Eclipse逐字解释代码的方法

String card = nextcard.toString();   //Becomes "Ace_Of_Hearts", for example
theImageButton.setImageResource(R.drawable.card);  //R.drawable.Ace_Of_Hearts is an image in the correct folder

遗憾的是,这不起作用。但是因为card变量是动态变化的,所以我不能硬编码一个特定的图像来设置按钮。那么,我应该如何设置图像呢?

您可以使用imagebutton选择器进行设置。 首先在res/drawable btn_selector.xml中创建选择器

<?xml version="1.0" encoding="utf-8"?>


现在,您可以使用此选择器作为图像按钮的src

<ImageButton
     android:id="@+id/button1"
     android:src="@drawable/btn_selector"
     android:layout_width="200dp"
     android:layout_height="126dp"/>

获取可提取目录中所有卡的id:

Integer ace_of_hearts_id = R.drawable.ace_of_hearts;
Integer ace_of_spades_id = R.drawable.ace_of_spades;
Integer queen_of_hearts_id = R.drawable.queen_of_hearts;
Integer ten_of_hearts_id = R.drawable.ten_of_hearts;
....
将ID和字符串名称作为键值对放在HashMap中:

    HashMap cardMap = new HashMap<String,Integer>();
    cardMap.put("ace_of_hearts",ace_of_hearts_id);
    cardMap.put("ace_of_spades" ace_of_spades_id);    
......

我还没有真正编译代码,所以可能会有错误,但这应该会给你一个基本的想法。

最好详细说明一下……在
中,如果有其他情况
改变了该图像,我有一个图像按钮,我想知道的是如何将图像设置为该图像按钮。这个网站上的其他答案是不够的,因为他们推荐了一些类似于“setImageResource(R.drawable.YOUR_IMAGE)”的东西,如果你不硬编码,这是行不通的。。
    HashMap cardMap = new HashMap<String,Integer>();
    cardMap.put("ace_of_hearts",ace_of_hearts_id);
    cardMap.put("ace_of_spades" ace_of_spades_id);    
......
String card = nextcard.toString();   //Becomes "Ace_Of_Hearts", for example
theImageButton.setImageResource(cardMap.get(card));  /