用android / java getIdentifier

时间:2011-01-22 23:47:28

标签: java android

我无法让getIdentifier使用类变量。这很奇怪,因为这有效:

public Drawable getStationIcon(Context context) {
    int resId = context.getResources().getIdentifier("m1m2_16", "drawable", "com.mypackage.namehere");
    Drawable drawable = context.getResources().getDrawable(resId);
    return drawable;
}

但这不是:

public Drawable getStationIcon(Context context) {
    int resId = context.getResources().getIdentifier(this.stationIcon, "drawable", "com.mypackage.namehere");
    Drawable drawable = context.getResources().getDrawable(resId);
    return drawable;
}

这也不是:

public Drawable getStationIcon(Context context) {
    String stationI = this.stationIcon;
    int resId = context.getResources().getIdentifier(stationI, "drawable", "com.mypackage.namehere");
    Drawable drawable = context.getResources().getDrawable(resId);
    return drawable;
}

this.stationIcon绝对等于m1m2_16。我尝试了其他替代方案,即使用""+this.stationIcon,但是当第一个参数是变量时,没有任何方法可行。有什么我想念的吗?

1 个答案:

答案 0 :(得分:2)

奇怪的是它可能会起作用:

getIdentifier("com.mypackage.namehere:drawable/" + this.stationIcon, null, null);

信用:https://stackoverflow.com/users/790997/idroid

Resources.getIdentifier() has unexpected behavior when name is numeric