Android PreferencesFragment with onchange Preference Listener

By | March 20, 2015

In my old post on Preferences Activity and sharedPreferences , there we have loaded preferences from a resource into PreferenceActivity using addPreferencesFromResource() method , but now this method has been deprecated as of API level 11 (HONEYCOMB) and No alternative method is provided in the method’s description because the preferred approach (as of API level 11) is to instantiate PreferenceFragment objects to load your preferences from a resource .

Below is the output of the sample example on PreferenceFragment

String Constant

file : string.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<resources>

    <string name=”app_name”>PrefsDemo</string>
    <string name=”hello_world”>Hello world!</string>
    <string name=”action_settings”>Settings</string>

    <string-array name=”colorNames”>
        <item name=”Red”>Red</item>
        <item name=”Yellow”>Yellow</item>
        <item name=”Green”>Green</item>
    </string-array>

    <string-array name=”colorValues”>
        <item name=”Red”>Red</item>
        <item name=”Yellow”>Yellow</item>
        <item name=”Green”>Green</item>
    </string-array>

</resources>

Preference

Define the Preference Activity UI inside “res/xml/”

file :preferences.xml

<PreferenceScreen xmlns:android=”http://schemas.android.com/apk/res/android” >

    <PreferenceCategory android:title=”Username” >
        <EditTextPreference
            android:dialogTitle=”Edit User”
            android:key=”username”
            android:summary=”Change UserName”
            android:title=”USERNAME” />
    </PreferenceCategory>

  <PreferenceCategory android:title=”Window” >
        <CheckBoxPreference
            android:key=”fullscreen”
            android:summary=”Enable FullScreen”
            android:title=”Fullscreen” />
    </PreferenceCategory>

  <PreferenceCategory android:title=”Background” >
        <ListPreference
            android:entries=”@array/colorNames”
            android:entryValues=”@array/colorValues”
            android:key=”color”
            android:summary=”Set Background Color”
            android:title=”Color” />
    </PreferenceCategory>

</PreferenceScreen>

  
Create a class PrefsFragment and extends to PreferenceFragment and add above defined preference xml through addPreferencesFromResource() method.
 

file :PrefsFragment.java

package com.tutorialsbuzz.prefsdemo;

import android.os.Bundle;
import android.preference.PreferenceFragment;

public class PrefsFragment extends PreferenceFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.preferences);
    }
}

Create a class SetPreferenceActivity and load the above defined PrefsFragment.

file :SetPreferenceActivity.java

package com.tutorialsbuzz.prefsdemo;

import android.app.Activity;
import android.os.Bundle;

public class SetPreferenceActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new PrefsFragment()).commit();
    }

}

XML Layout

Create a xml layout and add TextView to it .

file : activity_main.xml

<LinearLayout
    xmlns:android=”http://schemas.android.com/apk/res/android”
    xmlns:tools=”http://schemas.android.com/tools”
    android:layout_width=”match_parent”
    android:layout_height=”match_parent”
    android:orientation=”vertical”
    android:padding=”10dp” >

    <TextView
        android:id=”@+id/tv”
        android:layout_width=”wrap_content”
        android:layout_height=”wrap_content”
        android:textSize=”44sp” />

</LinearLayout>

MainActivity

  1. Create a class MainActivity and extend this class to Activity and inside the onCreate() method set the content of this activity with above defined XML Layout.
  2. Create option menu inside main activity , this menu contains menuitem called settings on click of that it opens our preference activity.
  3. Define a method call ApplySettings() by passing sharedpreference as parameter to it , inside this method will get preference data and apply .
  4. Define a subclass PrefsChangeListener inside MainActivity which implements OnSharedPreferenceChangeListener and override onSharedPreferenceChanged(SharedPreferences prefs,String key) now inside this method we call the ApplySettings().

file : MainActivity.java

package com.tutorialsbuzz.prefsdemo;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

public class MainActivity extends Activity {

    SharedPreferences sharedPrefs;
    PrefsChangeListener mPreferenceListener = null;

    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = (TextView) findViewById(R.id.tv);

        sharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(getApplicationContext());

        mPreferenceListener = new PrefsChangeListener();

        sharedPrefs
                .registerOnSharedPreferenceChangeListener(mPreferenceListener);

        ApplySettings(sharedPrefs);

    }

    private void ApplySettings(SharedPreferences sharedPrefs) {

        // EditText Preference
        String username = sharedPrefs.getString(“username”, “”);
        tv.setText(username);

        // CheckBox Preference
        Boolean fullscreen = sharedPrefs.getBoolean(“fullscreen”, false);
        if (fullscreen) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }

        // List Preferences
        String coloract = sharedPrefs.getString(“color”, “white”);
        View view = this.getWindow().getDecorView();
        if (coloract.equals(“Red”)) {
            view.setBackgroundColor(Color.RED);
        } else if (coloract.equals(“Yellow”)) {
            view.setBackgroundColor(Color.YELLOW);
        } else if (coloract.equals(“Green”)) {
            view.setBackgroundColor(Color.GREEN);
        }

    }

    // registerOnSharedPreferenceChangeListene
    class PrefsChangeListener implements OnSharedPreferenceChangeListener {

        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPrefs,
                String key) {
            ApplySettings(sharedPrefs);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            Intent i = new Intent(getApplicationContext(),
                    SetPreferenceActivity.class);
            startActivity(i);
        }
        return super.onOptionsItemSelected(item);
    }
}