我有一个徽标图片,我在我的应用程序的启动/欢迎屏幕上显示。当我最近使应用程序符合xxx-hdpi屏幕尺寸时,我遇到了一个奇怪的问题:
drawable
文件夹中。onCreate
功能中,我正在检查设备的密度并打开相应的图像:
float MAX_XX_SCALE = 3.0F; //Maximum scale of xx-hdpi screens.
ImageView img = (ImageView) findViewById(R.id.myImg); // ImageView containing the image.
if (getResources().getDisplayMetrics().density > MAX_XX_SCALE)
img.setImageDrawable(getResources().getDrawable(R.drawable.logo_large));
else
img.setImageDrawable(getResources().getDrawable(R.drawable.logo));`
但是我在执行应用程序时遇到NullPointerException
。
这是我的logcat
11-11 11:53:46.625: E/AndroidRuntime(919): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1955)
11-11 11:53:46.625: E/AndroidRuntime(919): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
11-11 11:53:46.625: E/AndroidRuntime(919): at android.app.ActivityThread.access$600(ActivityThread.java:122)
11-11 11:53:46.625: E/AndroidRuntime(919): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
11-11 11:53:46.625: E/AndroidRuntime(919): at android.os.Handler.dispatchMessage(Handler.java:99)
11-11 11:53:46.625: E/AndroidRuntime(919): at android.os.Looper.loop(Looper.java:137)
11-11 11:53:46.625: E/AndroidRuntime(919): at android.app.ActivityThread.main(ActivityThread.java:4340)
11-11 11:53:46.625: E/AndroidRuntime(919): at java.lang.reflect.Method.invokeNative(Native Method)
11-11 11:53:46.625: E/AndroidRuntime(919): at java.lang.reflect.Method.invoke(Method.java:511)
11-11 11:53:46.625: E/AndroidRuntime(919): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-11 11:53:46.625: E/AndroidRuntime(919): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-11 11:53:46.625: E/AndroidRuntime(919): at dalvik.system.NativeStart.main(Native Method)
11-11 11:53:46.625: E/AndroidRuntime(919): Caused by: java.lang.NullPointerException
11-11 11:53:46.625: E/AndroidRuntime(919): at com.project.android.WelcomeActivity.onCreate(WelcomeActivity.java:42)
11-11 11:53:46.625: E/AndroidRuntime(919): at android.app.Activity.performCreate(Activity.java:4465)
11-11 11:53:46.625: E/AndroidRuntime(919): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
11-11 11:53:46.625: E/AndroidRuntime(919): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1919)
这就是我在第42行:img.setImageDrawable(getResources().getDrawable(R.drawable.logo));
答案 0 :(得分:0)
正如你所说的
而且,该死的!我把它放在setContentView()
之前
因此,您的ImageView img
为空,因为您在设置内容视图之前尝试findViewById
,因此请
ImageView img = (ImageView) findViewById(R.id.myImg);
在onCreate方法中的setContentView
之后因为R.id.myImg
是内容视图的一部分。