Android嵌套了带ActionBar的PreferenceScreen

时间:2015-05-22 09:02:42

标签: android android-actionbar preferenceactivity

我的Android应用程序中有一个SettingsActivity。最初没有Actionbar,所以我实现了这个:

settings_toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    app:navigationContentDescription="@string/abc_action_bar_up_description"
    android:background="?attr/colorPrimary"
    app:navigationIcon="?attr/homeAsUpIndicator"
    app:title="@string/action_settings"
    />

SettingsActivity.java

public class SettingsActivity extends PreferenceActivity {

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        LinearLayout root = (LinearLayout)findViewById(android.R.id.list).getParent().getParent().getParent();
        Toolbar bar = (Toolbar) LayoutInflater.from(this).inflate(R.layout.settings_toolbar, root, false);
        root.addView(bar, 0); // insert at top
        bar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
}

它很好但仅适用于第一个PreferenceScreen。如果我有一个嵌套的PreferenceScreen,那么就没有ActionBar。 我怎样才能实现这一点,在嵌套的PreferenceScreen上还有一个带后退按钮的ActionBar?

它应该与API15 +和AppCombat兼容

原帖:How to add Action Bar from support library into PreferenceActivity?

1 个答案:

答案 0 :(得分:2)

我们可以使用简单的可点击首选项,而不是使用嵌套的PreferenceScreen,使其像“嵌套标题”一样工作;这将显示通常的ActionBar,因为它启动了PreferenceActivity实例,因此也将维护单窗格/双窗格导航样式。 这是一些简化的示例代码,其中包括ActionBar的后导航按钮设置:

<强> main_preferences.xml

<PreferenceScreen 
xmlns:android="http://schemas.android.com/apk/res/android"
android:orderingFromXml="true">
    <Preference      
    android:key="a_preference" />

    <!-- this is our "nested header", a simple Preference -->
    <Preference
    android:key="subscreen_preference" />

    <Preference       
    android:key="another_ preference" />

</PreferenceSreen>

<强> subscreen_preference.xml

<PreferenceScreen 
xmlns:android="http://schemas.android.com/apk/res/android"
android:orderingFromXml="true">
    <Preference      
    android:key="sub_preference" />

    <!-- etc -->

</PreferenceSreen>

<强> MyPreferenceActivity.class

public class MyPreferenceActivity extends AppCompatPreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //display back button. Fragments will handle its behavior (see below)
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

@Override
public void onBuildHeaders(List<Header> target) {
    loadHeadersFromResource(R.xml.pref_headers, target);
}

@Override
protected boolean isValidFragment(String fragmentName) {
    return MainPreferenceFragment.class.getName().equals(fragmentName) ||
           SubscreenFragment.class.getName().equals(fragmentName);
}


public static class MainPreferenceFragment extends PreferenceFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {

        //let the fragment intercept the ActionBar buttons:
        setHasOptionsMenu(true);

        addPreferencesFromResource(R.xml.main_preferences);

        findPreference("subscreen_preference").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {

            @Override
            public boolean onPreferenceClick(Preference preference) {
                //we create a Header manually:
                Header header = new Header();
                //mandatory fragment name:
                header.fragment = "com.foo.MyPreferenceActivity$SubscreenFragment";
                //subscreen title to be shown in the ActionBar
                header.titleRes = R.string.settings_fragment_title;
                //this will do the trick, no further action required:
                //we can ignore the second parameter
                ((MyPreferenceActivity)getActivity()).onHeaderClick(header, 0);
                return true;
            }
        });
    }

    //this will make the ActionBar back navigation button
    // behave like the system back button
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            if (!super.onOptionsItemSelected(item)) {
                getActivity().onBackPressed();
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

public static class SubscreenFragment extends PreferenceFragment {
    //usual implementation
    }
}

重要:如果你使用Proguard,请记得添加以下规则,否则isInvalidFragment()将返回false:

-keepnames class com.foo.MyPreferenceActivity$SubscreenFragment