我正在使用Android 2.1,并希望为MapsAvtivity添加一个后退按钮。我已经尝试了此页面上的内容[Display back button on action bar但应用程序崩溃了。我已经用另一个论坛推荐的AppCompatActivity替换了扩展FragmentActivity,但应用程序仍然崩溃。我知道它与动作栏有关,因为如果我删除它,应用程序就可以了。似乎操作栏为空。我被卡住并且已经多次启动了应用程序。这是错误:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pc.canda.theplacestosee/com.pc.canda.theplacestosee.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
at com.pc.canda.theplacestosee.MapsActivity.onCreate(MapsActivity.java:31)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694
答案 0 :(得分:3)
一些事情。确保您的acttivity扩展AppCompatActivity,确保您使用的样式有一个操作栏(您在清单中设置它)。
android:theme="@style/AppTheme"
确保使用正确的操作栏(ActionBar或SupportActionBar)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
或
getActionBar().setDisplayHomeAsUpEnabled(true);
最后,添加onOptionsItemSelected方法,以便后退按钮知道该怎么做。
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}