Friday, February 5, 2016

Android ListPreference Example

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="#e7f4f9"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go To Settings"
        />
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="80dp"
        android:textStyle="bold"
        android:fontFamily="sans-serif-condensed"
        />
</RelativeLayout>
res/xml/preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <EditTextPreference
        android:key="@string/sp_key_user_name"
        android:title="Input your name"
        android:icon="@drawable/ic_face_black_36dp"
        android:dialogIcon="@drawable/ic_insert_emoticon_black_36dp"
        />
    <!--
        ListPreference
            A Preference that displays a list of entries as a dialog.

            This preference will store a string into the SharedPreferences. This string will be
            the value from the setEntryValues(CharSequence[]) array.
    -->
    <!--
        android:entries
            The human-readable array to present as a list. Each entry must have a corresponding
            index in entryValues.

            Must be a reference to another resource, in the form "@[+][package:]type:name" or to a
            theme attribute in the form "?[package:][type:]name".

            This corresponds to the global attribute resource symbol entries.
    -->
    <!--
        android:entryValues
            The array to find the value to save for a preference when an entry from entries is
            selected. If a user clicks on the second item in entries, the second item in this array
            will be saved to the preference.

            Must be a reference to another resource, in the form "@[+][package:]type:name" or to
            a theme attribute in the form "?[package:][type:]name".

            This corresponds to the global attribute resource symbol entryValues.
    -->
    <!--
        android:defaultValue
            The default value for the preference, which will be set either if persistence is off
            or persistence is on and the preference is not found in the persistent storage.

            May be a reference to another resource, in the form "@[+][package:]type:name" or to a
            theme attribute in the form "?[package:][type:]name".

            May be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for
            a unicode character.

            May be an integer value, such as "100".

            May be a boolean value, either "true" or "false".

            May be a floating point value, such as "1.2".

            This corresponds to the global attribute resource symbol defaultValue.
    -->
    <!--
        android:icon
            The optional icon for the preference

            Must be a reference to another resource, in the form "@[+][package:]type:name" or to
            a theme attribute in the form "?[package:][type:]name".

            This corresponds to the global attribute resource symbol icon.
    -->
    <ListPreference
        android:key="@string/sp_key_foreground_color"
        android:title="Foreground Color"
        android:defaultValue="#00FFFF"
        android:entries="@array/foreground_color_names_array"
        android:entryValues="@array/foreground_color_values_array"
        android:summary="Select a foreground color"
        android:icon="@drawable/ic_palette_black_36dp"
        android:dialogIcon="@drawable/ic_palette_red_36dp"
        />
    <ListPreference
        android:key="@string/sp_key_background_color"
        android:title="Background Color"
        android:entries="@array/background_color_names_array"
        android:entryValues="@array/background_color_values_array"
        android:defaultValue="#DC143C"
        android:icon="@drawable/ic_palette_purple_36dp"
        android:dialogIcon="@drawable/ic_palette_green_36dp"
        android:summary="Choose a background color"
        />
</PreferenceScreen>
res/values/strings.xml

<resources>
    <string name="app_name">Android Example</string>
    <string name="title_activity_settings">Settings</string>
    <string name="title_activity_main">Android Example - ListPreference</string>

    <!-- SharedPreferences Keys -->
    <string name="sp_key_user_name">userName</string>
    <string name="sp_key_foreground_color">foregroundColor</string>
    <string name="sp_key_background_color">backgroundColor</string>
</resources>
res/values/array.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- foreground color names array -->
    <string-array name="foreground_color_names_array">
        <item>Aqua</item>
        <!--item>#00FFFF</item-->

        <item>Azure</item>
        <!--item>#F0FFFF</item-->

        <item>Beige</item>
        <!--item>#F5F5DC</item-->

        <item>Cornsilk</item>
        <!--item>#FFF8DC</item-->

        <item>Ivory</item>
        <!--item>#FFFFF0</item-->
    </string-array>

    <!-- foreground color values array -->
    <string-array name="foreground_color_values_array">
        <!--item>Aqua</item-->
        <item>#00FFFF</item>

        <!--item>Azure</item-->
        <item>#F0FFFF</item>

        <!--item>Beige</item-->
        <item>#F5F5DC</item>

        <!--item>Cornsilk</item-->
        <item>#FFF8DC</item>

        <!--item>Ivory</item-->
        <item>#FFFFF0</item>
    </string-array>


    <!-- background color names array -->
    <string-array name="background_color_names_array">
        <item>Blue</item>
        <!--item>#0000FF</item-->

        <item>Crimson</item>
        <!--item>#DC143C</item-->

        <item>Purple</item>
        <!--item>#800080</item-->

        <item>Green</item>
        <!--item>#008000</item-->

        <item>Coral</item>
        <!--item>#FF7F50</item-->
    </string-array>

    <!-- background color values array -->
    <string-array name="background_color_values_array">
        <!--item>Blue</item-->
        <item>#0000FF</item>

        <!--item>Crimson</item-->
        <item>#DC143C</item>

        <!--item>Purple</item-->
        <item>#800080</item>

        <!--item>Green</item-->
        <item>#008000</item>

        <!--item>Coral</item-->
        <item>#FF7F50</item>
    </string-array>
</resources>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Activity mActivity;

    private RelativeLayout mRelativeLayout;
    private Button mButton;
    private TextView mTextView;

    private SharedPreferences mSharedPreferences;


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

        // Get the application context
        mContext = getApplicationContext();

        // Get the activity
        mActivity = MainActivity.this;

        // Get the instance of SharedPreferences object
        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);

        // Get the widgets reference from XML layout
        mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
        mButton = (Button) findViewById(R.id.btn);
        mTextView = (TextView) findViewById(R.id.tv);

        // Set a click listener for the text view
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext,SettingsActivity.class);
                startActivity(intent);
            }
        });

        // Get the user's settings from SharedPreferences
        String userName = mSharedPreferences.getString(getString(R.string.sp_key_user_name), "Guest");

        // We retrieve foreground and background color value as a string
        String foregroundColor = mSharedPreferences.getString(getString(R.string.sp_key_foreground_color), "#000000");
        String backgroundColor = mSharedPreferences.getString(getString(R.string.sp_key_background_color),"#FFFFFF");

        // Update the text with SharedPreferences
        mTextView.setText("Hello " + userName);

        // Set a text color for text view based on user preference settings
        mTextView.setTextColor(Color.parseColor(foregroundColor));

        // Set a layout background color based on user preference settings
        mRelativeLayout.setBackgroundColor(Color.parseColor(backgroundColor));
    }
}
SettingsFragment.java

package com.cfsuman.me.androidcodesnippets;

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

/*
    PreferenceFragment
        Shows a hierarchy of Preference objects as lists. These preferences will automatically save
        to SharedPreferences as the user interacts with them. To retrieve an instance of
        SharedPreferences that the preference hierarchy in this fragment will use, call
        getDefaultSharedPreferences(android.content.Context) with a context in the same
        package as this fragment.
*/
public class SettingsFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        /*
            public void addPreferencesFromResource (int preferencesResId)
                Inflates the given XML resource and adds the preference hierarchy to the
                current preference hierarchy.

            Parameters
                preferencesResId : The XML resource ID to inflate.
        */
        // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.preferences);
    }
}
SettingsActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.os.Bundle;
import android.preference.PreferenceActivity;

/*
    PreferenceActivity
        This is the base class for an activity to show a hierarchy of preferences to the user.
        Prior to HONEYCOMB this class only allowed the display of a single set of preference

        This activity shows one or more headers of preferences, each of which is associated with a
        PreferenceFragment to display the preferences of that header. The actual layout and display
        of these associations can however vary; currently there are two major approaches it may take:

            On a small screen it may display only the headers as a single list when first launched.
            Selecting one of the header items will re-launch the activity with it only showing
            the PreferenceFragment of that header.

            On a large screen in may display both the headers and current PreferenceFragment
            together as panes. Selecting a header item switches to showing the correct
            PreferenceFragment for that item.
*/
public class SettingsActivity extends PreferenceActivity{
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        // Display the fragment as the main content
        getFragmentManager().beginTransaction()
                .replace(android.R.id.content,new SettingsFragment()).commit();
    }
}