I am trying to use the getActionBar(); method and I receive this error: required android.support.v7.app.ActionBar found android.app.ActionBar . How can I correct this?
问题:
回答1:
This error is occurring because you are creating an object and passing it to a different class reference variable. Because getActionManager
gives the object of android.app.ActionBar
but you are trying to assign android.app.ActionBar
class object to android.support.v7.app.ActionBar
.
But both these classes provide the same functionality. android.support.v7.app.ActionBar
Class is used when our uses-sdk min version is less the api 11. to get the object of ActionBar below api 11 we need android.support.v7.app.ActionBar
class object.
To get Action bar you need to follow one of two approaches.
import android.support.v7.app.ActionBar
and usegetSupportActionBar()
method od activity.go to AndroidManifest.xml file and change
<uses-sdk android:minSdkVersion="11" android:targetSdkVersion="19" />
and importandroid.app.ActionBar
and usegetActionBar()
回答2:
If supporting API levels lower than 11 and you will have to add the support v4 library in your project to used an actionbar.
import android.support.v7.app.ActionBar
If supporting only API level 11 and higher:
import android.app.ActionBar
For more information go to Official Docs
回答3:
Make sure that you have minimum api level in your manifest file is above 11. Because the package android.support.v7.app.ActionBar
is only supported in api level below 11.
So if you want to use an ActionBar from import android.app.ActionBar
then you must be having minimun api level 11 in your manifest file. Otherwise you will have to add the support v4 library in your project to user an actionbar from android.support.v7.app.ActionBar
package.
回答4:
Make sure your app has app bar or title bar, check you app theme at manifest file or at your style.xml if in your style like this:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- your style --> </style>
It will fine when use ActionBar actionbar = getSupportActionBar();
But if on your style like this:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- your style--> </style>
it will throw null exception when use ActionBar actionbar = getSupportActionBar();
Make sure you use import android.support.v7.app.ActionBar
回答5:
If running api 11 and higher
import android.app.ActionBar;
also if it states that it already exists be sure to remove it