ImageView上的setPadding崩溃了活动

时间:2012-12-29 11:53:03

标签: android nullpointerexception imageview android-actionbar-compat

我使用actionbarcompat在pre honeycomp设备上也有一个操作栏。

由于主页图标和操作栏标题之间​​没有空格,我将其添加到我的活动中:

// add padding to the right of home item
ImageView view = (ImageView)findViewById(android.R.id.home);
view.setPadding(0, 0, 10, 0);

实际上第二行(setPadding)导致崩溃。

它在Jelly Bean设备上运行良好。但我得到一个Null Pointer异常,例如在Android 2.3设备。

这是崩溃的logcat输出:

12-29 11:44:36.968: E/AndroidRuntime(329): FATAL EXCEPTION: main
12-29 11:44:36.968: E/AndroidRuntime(329): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.GetRichOrDieSmoking/com.GetRichOrDieSmoking.MainScreen}: java.lang.NullPointerException
12-29 11:44:36.968: E/AndroidRuntime(329):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
12-29 11:44:36.968: E/AndroidRuntime(329):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
12-29 11:44:36.968: E/AndroidRuntime(329):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
12-29 11:44:36.968: E/AndroidRuntime(329):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
12-29 11:44:36.968: E/AndroidRuntime(329):  at android.os.Handler.dispatchMessage(Handler.java:99)
12-29 11:44:36.968: E/AndroidRuntime(329):  at android.os.Looper.loop(Looper.java:123)
12-29 11:44:36.968: E/AndroidRuntime(329):  at android.app.ActivityThread.main(ActivityThread.java:3683)
12-29 11:44:36.968: E/AndroidRuntime(329):  at java.lang.reflect.Method.invokeNative(Native Method)
12-29 11:44:36.968: E/AndroidRuntime(329):  at java.lang.reflect.Method.invoke(Method.java:507)
12-29 11:44:36.968: E/AndroidRuntime(329):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-29 11:44:36.968: E/AndroidRuntime(329):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-29 11:44:36.968: E/AndroidRuntime(329):  at dalvik.system.NativeStart.main(Native Method)
12-29 11:44:36.968: E/AndroidRuntime(329): Caused by: java.lang.NullPointerException
12-29 11:44:36.968: E/AndroidRuntime(329):  at com.GetRichOrDieSmoking.MainScreen.onCreate(MainScreen.java:463)
12-29 11:44:36.968: E/AndroidRuntime(329):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-29 11:44:36.968: E/AndroidRuntime(329):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
12-29 11:44:36.968: E/AndroidRuntime(329):  ... 11 more

2 个答案:

答案 0 :(得分:2)

android.R.id.home仅在API级别11中引入。因此无法在Android 2.3中创建视图。因此,当您尝试在空视图上设置填充时,在以下行中,您将获得NullPointerException

答案 1 :(得分:0)

您可能无法访问主视图,原因可能是API级别。

使用第三方库作为操作栏以支持低API级别。

我强烈建议您使用actionBarSherlock