Android using Drawables in an Enum

*爱你&永不变心* 提交于 2019-12-22 09:59:28

问题


I have a project that I have to design an array of coins and work with it. My GUI looks like this - http://i.imgur.com/eRzN3Sb.png

I want to be able to load the appropriate image from the coinArray for each coin. basically i want to be able to say coinView.setBackgroundResource(coinArray[x].image) i assume i need to somehow use a drawable object and i was hoping its possible to include it in my enum class. the enum class looks like

public enum Currency {
    Penny(1), Nickel(5), Dime(10), Quarter(25);
    private int value;
    private Currency(int value) {
            this.value = value;

    }

}

Each coin in the array has a currency value so i can compute them. I'd like to add a drawable or some other object that will allow me to refernce the correct image for each coin.

Thank you


回答1:


public enum Currency {
    Penny(1,R.drawable.xxx), Nickel(5,R.drawable.yyy),...;
    private int value;
    private int image
    private Currency(int value,int drawableId) {
            this.value = value;
            this.image=drawableId;

    }
    public int getImage(){
       return image;
    }

}

There are many ways you can do this. This is one of them. to use it:

coinView.setImageResource(coinArray[x].getImage());


来源:https://stackoverflow.com/questions/15182045/android-using-drawables-in-an-enum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!