我有一个名为expenseType的对象模型:
public class ExpenseType {
private String gridText;
public enum type {
FOOD(Constants.EXPENSE_TYPE_FOOD, R.drawable.food_blue, R.drawable.food),
FLOWERS(Constants.EXPENSE_TYPE_FLOWERS, R.drawable.flowers_blue, R.drawable.flowers),
GROCERIES(Constants.EXPENSE_TYPE_GROCERIES, R.drawable.groceries_blue, R.drawable.groceries),
HOLIDAY(Constants.EXPENSE_TYPE_HOLIDAY, R.drawable.holiday_blue, R.drawable.holiday),
PHARMACY(Constants.EXPENSE_TYPE_PHARMACY, R.drawable.pharmacy_blue, R.drawable.pharmacy),
BILLS(Constants.EXPENSE_TYPE_BILLS, R.drawable.bills_blue, R.drawable.bills),
CLOTHES(Constants.EXPENSE_TYPE_CLOTHES, R.drawable.clothes_blue, R.drawable.clothes),
TRANSPORT(Constants.EXPENSE_TYPE_TRANSPORT, R.drawable.transport_blue, R.drawable.transport),
ITEMS(Constants.EXPENSE_TYPE_ITEMS, R.drawable.items_blue, R.drawable.items),
OTHERS(Constants.EXPENSE_TYPE_OTHERS, R.drawable.others_blue, R.drawable.others);
private String expenseKey;
private int drawableBlue, drawableWhite;
type(String expenseKey, @DrawableRes int drawableBlue, @DrawableRes int drawableWhite) {
this.expenseKey = expenseKey;
this.drawableBlue = drawableBlue;
this.drawableWhite = drawableWhite;
}
public String getKey() {
return expenseKey;
}
public int getDrawableBlue() {
return drawableBlue;
}
public int getDrawableWhite() {
return drawableWhite;
}
}
public ExpenseType(String gridText) {
this.gridText = gridText;
}
public String getGridText() {
return gridText;
}
public void setGridText(String gridText) {
this.gridText = gridText;
}
}
字符串 gridText 被写入数据库内,但我不想将可绘制值也添加到数据库中,因此我创建了具有可绘制变体的枚举。现在,在回收 View 适配器内,如何从枚举访问 getDrawableBlue() 以便设置与我的费用类型对应的图标?
我在适配器中有此代码:
private void checkSelect(ExpenseType expenseType) {
if(positionSelected == getAdapterPosition()){
gridIcon.setImageResource(????????);
return;
}
我怎样才能访问那个 setter/getter 而不是?????????这样我就可以将我的可绘制值存储在该枚举中?
最佳答案
这看起来像是您的类设计中的一个小问题。
您的枚举 type
是您的 ExpenseType
中的嵌套类类(class)。
(注意:因为它是一个枚举,所以它隐式是一个 static
嵌套类型)。
为了让您能够调用 type
的访问器,您将需要以某种方式引用其特定类型。
一种方法是使用 type
作为 ExpenseType
的实例字段,非常类似于String gridText
.
然后您需要绑定(bind)特定的 type
输入您的ExpenseType
实例(我知道,这在语义上会令人困惑,但我没有命名你的变量:)。
换句话说,ExpenseType
的每个实例有自己的type
字段分配了一种类型...错误.. type
。
所以 ExpenseType
的实例 1有一个FOOD
其值 type
, ExpenseType
的实例 2有一个FLOWERS
其值 type
等
然后您可以添加一个 getter 并引用 drawableBlue int
在checkSelect
通过调用:
// assuming field type can't be null
expenseType.getType().getDrawableBlue()
关于java - 如何使用枚举的 getter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56835017/