Android getActionBar与getSupportActionBar? [英] Android getActionBar vs getSupportActionBar?
问题描述
这是我的代码:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
//android.support.v7.app.ActionBar actionBar = getSupportActionBar();
//actionBar.setTitle("Android");
ActionBar actionBar = getActionBar();
actionBar.setTitle("Droid");
}
使用getSupportActionBar()时,我的应用程序可以在kitkat和其他新版本上正常运行,但是使用getActionBar会导致错误.
While using the getSupportActionBar() my app runs just fine with kitkat and other new versions but using getActionBar results into an error.
这是错误:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.hide()' on a null object reference
at com.github.domain.geoquiz.QuizActivity.onCreate(QuizActivity.java:57)
at android.app.Activity.performCreate(Activity.java:5933)
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
为什么?从android文档:
Why? From android documentations :
警告:请确保您导入了ActionBar类(以及相关的API) 从适当的程序包中:
Caution: Be certain you import the ActionBar class (and related APIs) from the appropriate package:
如果支持的API级别低于11: 导入android.support.v7.app.ActionBar
If supporting API levels lower than 11: import android.support.v7.app.ActionBar
如果仅支持API级别 11或更高版本:导入android.app.ActionBar
If supporting only API level 11 and higher: import android.app.ActionBar
现在为什么这个应用程序崩溃了?
Now why this app is crashing?
推荐答案
如果您使用的是AppCompat,则无论您的应用运行的是哪个Android版本,都必须调用getSupportActionBar()
.
If you are using AppCompat you always have to call getSupportActionBar()
no matter which Android Version your App is running.
您定位到哪个Android版本?
Which Android versions do you target?
我建议您使用新的工具栏代替ActionBar ,因为它使用起来更灵活.
I would advise you to use the new Toolbar instead of ActionBar, because it's way more flexible to use.
这篇关于Android getActionBar与getSupportActionBar?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!