Saturday, May 26, 2018

Android Preferences Screen - Few quick notes:

First of all, Android gives a good boiler plate activity for showing the settings. Its very well architectured.
Below given is some quick tips on certain aspects of it.

- With the boiler plate code, it comes with a list of options and when click on it show the fragments associated with it.
If we just need to show only one fragment, have the below line

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

The last line forces the system to not show the default list of options, instead show the NotificationPreferenceFragment directly

For showing a Checkox preference, below few lines will do


public static final String KEY_PREF_NEW_MSG_NOTIFICATIONS = "notifications_new_message";
//note that the key should match the key specified in the xml file




   
            android:defaultValue="true"
        android:key="notifications_new_message"
        android:title="@string/pref_title_new_message_notifications" />


Now we need to bind the ui with the stored values. In-order to do that, below bindPReferenceSummary code will help.

 @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.pref_notification);
            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(KEY_PREF_NEW_MSG_NOTIFICATIONS));
        }


references:
https://developer.android.com/guide/topics/ui/settings

No comments:

Post a Comment