Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show up/back button on android nested PreferenceScreen?

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?

like image 972
lisovaccaro Avatar asked Jan 07 '13 06:01

lisovaccaro


2 Answers

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.

like image 160
liucheia Avatar answered Nov 15 '22 15:11

liucheia


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)
like image 37
ThanksMister Avatar answered Nov 15 '22 15:11

ThanksMister