Search code examples
androidandroid-preferencespreferenceactivity

Android AppCompatPreferenceActivity - flat settings list without subcategories/headers


I have added SettingsActivity to my project. By default, Android Studio has created 3 categories with 3 headers. When I tap to category, new settings screen appears. I don't want that. My app has very limited settigns options, so I want to get only flat settings list, without any headers and categories.

What I found, not working or deprecated api. Can you point me right, valid direction how to implement flat settings screen without using any deprecated api?


Solution

  • In onCreate() method of SettingActivity add general fragment and do the changes whatever you like in GeneralPreferenceFragment

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setupActionBar();
            this.getFragmentManager().beginTransaction().replace(android.R.id.content, new GeneralPreferenceFragment()).commit();
        }
    

    And override onOptionItemSelected in GeneralPreferenceFragment like this:

        public static class GeneralPreferenceFragment extends PreferenceFragment {
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                addPreferencesFromResource(R.xml.pref_general);
                setHasOptionsMenu(true);
    
                // Bind the summaries of EditText/List/Dialog/Ringtone preferences
                // to their values. When their values change, their summaries are
                // updated to reflect the new value, per the Android Design
                // guidelines.
                bindPreferenceSummaryToValue(findPreference("your_key"));
            }
    
            @Override
            public boolean onOptionsItemSelected(MenuItem item) {
                int id = item.getItemId();
                if (id == android.R.id.home) {
                    getActivity().onBackPressed();
                }
                return super.onOptionsItemSelected(item);
              }
    }