Show up/back button on android nested PreferenceSc

2019-02-06 08:30发布

问题:

I have a two level PreferenceScreen:

<PreferenceScreen>
general settings
   <PreferenceScreen android:key="adv_settings">
   more advanced settings
   </PreferenceScreen>
</PreferenceScreen>

My problem is that the second screen doesn't show the back/up button on the action bar automatically. How do I make the up button appear on adv_settings?

回答1:

You can add the arrow by writing a custom ActionBar style to be used with your application theme.

res/values-v11/styles.xml: (or add these to your existing styles.xml)

<?xml version="1.0" encoding="utf-8"?>
<resources>    
  <style name="MyTheme" parent="@android:style/Theme.Holo.Light">
    <item name="android:actionBarStyle">@style/MyActionBar</item>
  </style>

  <style name="MyActionBar" parent="@android:style/Widget.Holo.ActionBar">
    <item name="android:displayOptions">showHome|homeAsUp|showTitle</item>
  </style>
</resources>

Then apply this theme in your AndroidManifest.xml:

<application android:theme="@style/MyTheme">


Note: The obvious way to add this arrow should be to call:

getActionBar().setDisplayHomeAsUpEnabled(true);

once the second screen has loaded, but I think there's an Android bug where getActionBar() always returns the first-tier ActionBar object, as opposed to the one that is currently visible, so setting the arrow dynamically fails.



回答2:

This may be more work, but you could create two PreferenceAtivity files each with their own PreferenceFragment. Each PreferenceFragment will have its own PreferenceScreen XML (the first level screen, and the second. level screen). From the firsts level screen you launch the second PreferenceActivity with an Intent within the tag. In the second PreferenceActivity you can set the home icon by doing this:

ActionBar bar = getActionBar();
bar.setDisplayHomeAsUpEnabled(true);

and then also had a handler for the home button:

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    if (item.getItemId() == android.R.id.home) {
        finish();
    }

    return false;
}

Assets:

FirstPreferenceActivty
FirstPreferenceFragment
pref_first.xml (layout with PreferenceScreen and Prefernce nodes)

SecondPreferenceActivty
SecondPreferenceFragment
pref_second.xml (layout with PreferenceScreen and Prefernce nodes)


回答3:

If the button does not come automatically, you could add it manually like done on these links:

Android: How can make custom PreferenceScreen?

http://pastebin.com/334Eip35

There is a example code in second answer of that SO question and the snippet in it is taken probably from the another pastebin location.