How to create android settings screen using PreferenceFragment





Giving people the power to change your application’s preferences, is not only professional but also neat and makes your application flexible. Today we are going to learn how to create a simple android settings screen using PreferenceFragment. Creating an android settings screen is way too simple as most of the code is provided for by Android itself.

Understanding Android Settings Screen

The Android settings screen is a platform that gives users an opportunity to set app preferences with an ease. Android Settings screen is made of four main preferences as shown below:

Read Also Automatic phone number verification like whatsapp and Telegram. Android tutorial

  1. CheckBoxPreference: returns true if checked and false if unchekcked and has 3 main attribues: android:key, android:title and android:summary, it may also contain defaultVAlue attribue, which is false by default
  2. SwitchPreference: Shares same behaviour with CheckBoxPreference
  3. ListPreference: List prefernence returns string value. It contains 5 attributes:
    android:entries – Android entries must be defined in ListPreference, failure to which app will crash.
    android:entryValues – android entery values must also be defined. Enteries and entery values are string arries defined in the strings resources file
    Other attributes includes: title, Summery and Key
  4. EditTextPreference: EditTextPreference returns string value as name suggests this is just a normal EditText used to save string values like passwords, usernames, emails and so on. It contains 3 main attributes:title, Summery and Key

How to create android settings screen using PreferenceFragment

The Android settings screen is built on the fragment and hence, there must be an activity where this fragment life cycles will take place. Actually, go ahead and create basic activity and name it SettingsActivity, having done that, also create android resources directory and name it xml as shown in the images below:



Read Also How to change language in android programatically

Creating xml resources directory step one

Android settings screen Step One
Android settings screen Step One

Creating xml resources directory step Two

Android settings screen Step two
Android settings screen Step two

Creating xml resources directory step Three

Android Settings Screen Step 3
Android Settings Screen Step 3

XML Resource file

Having created XML resource directory, the next thing would be to create XML resource file. Right click on XML resource directory and create new XML resource file, call it settings_ui.xml. Paste this code into the XML resource file.

settings_ui.xml

Android Settings Screen - settings_ui

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <CheckBoxPreference
        android:defaultValue="true"
        android:key="splash"
        android:summary="Check to allow start screen every time application starts"
        android:title="Allow Splash Screen" />

    <CheckBoxPreference
        android:key="uncheckedCheckbox"
        android:summary="This is unchecked settins checkbox"
        android:title="Unchecked Settings CheckBox" />

    <SwitchPreference
        android:defaultValue="true"
        android:key="notifications"
        android:summary="Turn on or off application notifications"
        android:title="Notifications" />

    <ListPreference
        android:entries="@array/list_preference_entries"
        android:entryValues="@array/list_preference_entries"
        android:key="listPreference"
        android:summary="list preference example summery explanation"
        android:title="List Preference Example" />

    <EditTextPreference
        android:key="password"
        android:summary="Set system password to protect your software"
        android:title="System Password [Edit Text Preference]" />


</PreferenceScreen>


We have already explained what these preferences mean, next add this code to your SettingsActivity.java activity

package brywa.com.brywa;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;


public class SettingsActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_layut);

        // our settings activity must come here

        Fragment fragment = new SettingsHolder();
        // this fragment must be from android.app.Fragment, 
        // if you use support fragment, it will not work

        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        if (savedInstanceState == null) {
            // when saved instance state is null, that means
            // activity is created for the first time, so basically
            // add the fragment to activity if and only if activity is new
            // when activity rotates, do nothing

            transaction.add(R.id.settings_holder, fragment, "settings_screen");
        }

        transaction.commit();


    }

    // below inner class is a fragment, which must be called in the main activity
    public static class SettingsHolder extends PreferenceFragment {
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // here we should call settings ui
            addPreferencesFromResource(R.xml.settings_ui);

        }
    }
}

Layout for SettingsActivity.java activity should look like this

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/settings_holder"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    
    <!-- this is where we will add
    our fragment --> 
    
</LinearLayout>

How to access android settings across the full application

Having created android settings screen successfully, the next thing would be how to use these settings in a way that is seamless. First, we are going to treat all settings as a single object, that this object will be responsible for all settings in the whole application.

Make sure you also read: Android press back again to exit application

Go ahead and create a new class and call it DefaultSettings.java. Default settings will get data from our settings screen as shown in the code below. Please make sure you read comments inside the code.

package brywa.commm.brywa;


import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class DefaultSettings {
    private static SharedPreferences sharedPreferences;

    // create one method that will instantiate sharedPreferecdes
    private static void getSharedPreferencesInstance(Context context) {
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    }

    // this is for the checked CheckPreference, please note our default value
    // for the checked preference is true, make your default value below to be true
    // if the default value was false or maybe the checkbox was unchecked, we could have
    // used false as our default value
    public static boolean splashScreenEnabled(Context context) {
        getSharedPreferencesInstance(context);
        return sharedPreferences.getBoolean("splash", true);
        //return sharedPreferences.getBoolean(key, defaultValue);
        // this is the key in the settings_ui.xml for a specific preference
    }

    // this is for switchPreference
    public static boolean notificationEnanbled(Context context) {
        getSharedPreferencesInstance(context);
        return sharedPreferences.getBoolean("notifications", true);
    }

    // for list preference
    // remember list preference will return entryValues, that means,
    // values are strings
    public static String getListPrefereceValue(Context context) {
        getSharedPreferencesInstance(context);
        return sharedPreferences.getString("listPreference", ""); // there was no default value, we can leave default value empty
    }

    // editTextPreferece [password]
    public static String getUserPassword(Context context) {
        getSharedPreferencesInstance(context);
        return sharedPreferences.getString("password", "");
    }
}



How to access your android settings using DefaultSettings Class

To access your settings, you would just call your static methods, let’s say for example you want to check if splash is enabled in the settings and you want to do this in the splash activity, you could just do this:

Make sure you also read: How to implement endless scrolling RecyclerView like gmail app

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        if(DefaultSettings.splashScreenEnabled(this)){
            // this means the splash is check box is checked
            splash();
        } else {
            // do something else
        }
        
        
    }
}

Conclusion

That’s how to create android settings screen if you got any question, kindly ask the commenting system below