如何在Android Studio中将ImageView/ImageButton引用为枚举值

3

我有这6张彩色图片,将用作ImageView或ImageButton它们的编码如下:

R.drawable.bluePeg
R.drawable.redPeg
R.drawable.greenPeg
R.drawable.purplePeg
R.drawable.brownPeg
R.drawable.yellowPeg

我希望它们与枚举值相关联,这样我就可以更好地在数组中进行比较,就像这样:

我希望它们与枚举值相关联,这样我就可以更好地在数组中进行比较,就像这样:

public enum Colours {
    RED, BLUE, YELLOW, BROWN,
    GREEN, PURPLE;
}

我的问题是如何使用枚举将这些图像与正确的值链接起来,以便我可以开始使用数组更好地引用它们。
希望这有意义,谢谢。
2个回答

5
你可以为枚举类型 Colours 创建构造函数:
public enum Colours {

    RED(R.drawable.redPeg), ... BLUE(R.drawable.bluePeg);

    private final int drawable;

    private Colours(int drawable) {
        this.drawable = drawable;
    }

    public int getDrawable() {
        return this.drawable;
    }
}

0
可以使用HashMap来实现类似以下的操作:
Map<String, Integer> colors = new HashMap<String, Integer>();
colors.put("RED", R.drawable.redPeg);
// etc, put all the values

获取以下数值:

colors.get("RED"); // will return R.drawable.redPeg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接