Search code examples
androidsharedpreferencesandroid-preferencesandroid-settings

Multine line label on settings


I would like to crate a settings Activity with items with Title and subtitle.

I've checked a lot in documentation and even other posts here and people say it's not possible... android default settings page has a lot of it: enter image description here

sorry for the picture in portuguese, but what is written there doesn't matter, the point is the settings page built on android has plenty of titile/subtitle items (and it happens in many other screens)

I would like to achieve it using android default Preference api. is that possible?


Solution

  • Yes it is possible. One fast solution is the following (that might be improvied and tuned according your needs):

    public class SettingsActivity extends Activity {
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_settings);
            if (savedInstanceState == null) {
                getFragmentManager().beginTransaction()
                        .add(R.id.settings_fragment, new PrefsFragment()).commit();
            }
        }
    
        public static class PrefsFragment extends PreferenceFragment {
    
            public PrefsFragment(){}
    
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
    
                // Load the preferences from an XML resource
                addPreferencesFromResource(R.xml.settings);
            }
        }
    }
    

    activity_settings.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <fragment
            android:id="@+id/settings_fragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:name="com.vb.myapplication.SettingsActivity$PrefsFragment" />
    </LinearLayout>
    

    settings.xml

    <?xml version="1.0" encoding="utf-8"?>
    <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
        <PreferenceCategory
            android:key="keyCategory"
            android:title="titleCategory">
    
            <CheckBoxPreference
                android:key="keyCheckPreference"
                android:title="titlePreference"
                android:summary="summaryPreference"
                android:defaultValue="false"/>
        </PreferenceCategory>
    </PreferenceScreen>