问题
I need to check if the overlay feature has been set on an ActionBarCompat instance. The getWindow().hasFeature() method is only available on API 11 and up.
How can I check the feature on API < 11 ?
EDIT: Based on the comment, the getFeatures method should be available from API 1 but it is protected scope and I need to access the feature from another class. The hasFeature method, the one I need to use, on the other hand is API 11 and above only. This is what Android Studio shows me and the app crashes on a 2.3.3 device.
FYI, the activity class used here is a custom class that extends ActionBarActivity from the ActionBarCompat library. Don't know if that should make a difference.
回答1:
You can access private methods using The Reflection API.
boolean hasFeature(int feature) {
Window window = getWindow(); //get the window instance.
if (android.os.Build.VERSION.SDK_INT >= 11) { // if we are running api level 11 and later
return window.hasFeature(feature); //call hasFeature
} else {
try {
Class c = window.getClass();
Method getFeatures = c.getDeclaredMethod("getFeatures");//get the getFeatures method using reflection
getFeatures.setAccessible(true);//make it public
Integer features = getFeatures.invoke(window, null); //invoke it
return (features.intValue() & (1 << feature)) != 0; //check if we have the feature and return the result.
} catch (Exception e) {
return false;//in case invocation fails with any reason
}
}
}
回答2:
Have you tried using Support Library.
Action bar is introduced in android 3.0 (API level 11), but if you want your app to support action bar in older versions too, then use Support Library to make it compatible with older versions (Android 2.1 and above)
来源:https://stackoverflow.com/questions/23925708/getwindow-hasfeature-on-api-11