How to add Action Bar from support library into Pr

2019-01-05 07:40发布

Action Bar compatibility has been added into support library, revision 18. It now has ActionBarActivity class for creating activities with Action Bar on older versions of Android.

Is there any way to add Action Bar from support library into PreferenceActivity?

Previously I used ActionBarSherlock and it has SherlockPreferenceActivity.

8条回答
混吃等死
2楼-- · 2019-01-05 08:07

I was able to get android.app.Actionbar by using getActionBar(). It returned a null value at first... then I went to the manifest and changed the theme to:

android:theme="@style/Theme.AppCompat"

Then I was able to have the actionbar again. I'm assuming this will only work for certain build levels. So you might want to do a check for the build number or check if the value returned is null.

It'll be fine for me because the app I'm working on is for ICS/4.0+.

查看更多
Juvenile、少年°
3楼-- · 2019-01-05 08:11

Problem Background:

The OP wants to know how can we put MenuItems in the ActionBar of PreferenceActivity for pre-Honeycomb because Android's support library has a bug which doesn't allow this to happen.

My Solution:

I've found a much cleaner way, than already proposed, to achieve the target (and found it in the Android Docs):

android:parentActivityName

The class name of the logical parent of the activity. The name here must match the class name given to the corresponding element's android:name attribute.

The system reads this attribute to determine which activity should be started when the use presses the Up button in the action bar. The system can also use this information to synthesize a back stack of activities with TaskStackBuilder.

To support API levels 4 - 16, you can also declare the parent activity with a element that specifies a value for "android.support.PARENT_ACTIVITY". For example:

<activity
    android:name="com.example.app.ChildActivity"
    android:label="@string/title_child_activity"
    android:parentActivityName="com.example.myfirstapp.MainActivity" >
    <!-- Parent activity meta-data to support API level 4+ -->
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.app.MainActivity" />
</activity>

Now do what you would normally do in your onOptionsItemSelected(). Since it's a part of Android Docs, it has no side-affects.

Happy coding. :)

Update:

This solution no longer works if you're targeting Lollipop. If you're using AppCompat, this answer is what you should be looking for.

查看更多
登录 后发表回答