ADVERTISEMENT

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 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 unchecked and has 3 main attributes: android: key, android: title and android: summary, it may also contain default value attribute, which is false by default
  2. SwitchPreference: Shares same behavior with CheckBoxPreference
  3. ListPreference: List preference returns a string value. It contains 5 attributes:
    android: entries – Android entries must be defined in ListPreference, failure to which app will crash.
    android:entryValues – android entry values must also be defined. Entries and entry values are string array defined in the strings resources file
    Other attributes include: title, Summary, and Key
  4. EditTextPreference: EditTextPreference returns string value as the 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, Summary, 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 languages in android programmatically

Creating XML resources directory 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

XML Resource file

Having created an XML resource directory, the next thing would be to create an XML resource file. Right-click on XML resource directory and create a 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





AdBlock Detected!
This site depends on revenue from ad impressions to survive. If you find this site valuable, please consider disabling your ad blocker or pausing adblock for this website.