Android getActionBar vs getSupportActionBar?

匿名 (未验证) 提交于 2019-12-03 01:33:01

问题:

Here is my code:

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"); } 

While using the getSupportActionBar() my app runs just fine with kitkat and other new versions but using getActionBar results into an error.

Here is error:

Why? From android documentations :

Caution: Be certain you import the ActionBar class (and related APIs) from the appropriate package:

If supporting API levels lower than 11: import android.support.v7.app.ActionBar

If supporting only API level 11 and higher: import android.app.ActionBar

Now why this app is crashing?

回答1:

If you are using AppCompat you always have to call getSupportActionBar() no matter which Android Version your App is running.

Which Android versions do you target?

I would advise you to use the new Toolbar instead of ActionBar, because it's way more flexible to use.



回答2:

If you are extending AppCompatActivity then you are providing backward support for older Android versions and for that you have to use getSupportActionBar().

If you are importing android.app.ActionBar then you have to use getActionBar() and if you are importing android.support.v7.app.ActionBar then you have to use getSupportActionBar().

Note: By using android.support.v7.app.ActionBar, you can provide backward support for older Android versions.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!