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

hyb*_*d94 3 java enums android android-studio

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

R.drawable.bluePeg
R.drawable.redPeg
R.drawable.greenPeg
R.drawable.purplePeg
R.drawable.brownPeg
R.drawable.yellowPeg
Run Code Online (Sandbox Code Playgroud)

我希望它们链接到枚举值,以便我可以更好地在数组中比较它们,如下所示:

public enum Colours {
    RED, BLUE, YELLOW, BROWN,
    GREEN, PURPLE;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是如何使用枚举将这些图像链接到正确的值,以便我可以开始使用数组以便更好地引用它们。

希望这是有道理的,谢谢。

Max*_*Max 5

您可以为枚举颜色创建构造函数:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)