使用Context获取Drawable的标识符会产生空指针异常

时间:2013-09-07 04:26:57

标签: android nullpointerexception drawable android-context

这段代码看起来似乎不切实际,但我对其进行了简化,以便我能更好地理解答案。我得到一个空指针异常,并无法弄清楚为什么。我的drawable文件夹中有president1.png。对于“president1”,我也试过了president1.png。方法flipCard(View v)由一个按钮按下来调用android:onClick =“flipCard”。有什么建议吗?

public void flipCard(View v){
card1.setImageResource(getIdentifier(getBaseContext()));
}


public static int getIdentifier(Context context){
return context.getResources().getIdentifier("president1", "drawable", context.getPackageName());
}

<ImageButton
    android:id="@+id/card1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/card8"
    android:layout_toLeftOf="@+id/card2"
    android:background="@null"
    android:onClick="flipCard"
    android:src="@drawable/facedown" />

1 个答案:

答案 0 :(得分:1)

尝试使用

card1.setImageResource(getIdentifier(v.getContext()));

而不是

card1.setImageResource(getIdentifier(getBaseContext()));

这会导致您的代码使用View正在运行的Context。

我很确定问题实际上是您文件名中的.png,因为您应用中的任何上下文都可以访问资源(除非您在调用{1}}之前调用了Activity已创建,在这种情况下,它将返回null)。

相关问题