Thursday, February 4, 2016

Android Preference 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="#e6f1e0"
    >
    <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="75dp"
        />
</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"
        />
    <CheckBoxPreference
        android:key="@string/sp_key_show_bold_text"
        android:title="Display bold text?"
        android:defaultValue="false"
        android:summary="Select whether the app display bold text."
        />
    <CheckBoxPreference
        android:key="@string/sp_key_show_red_text_color"
        android:title="Display red color text?"
        android:defaultValue="false"
        />
</PreferenceScreen>
res/values/strings.xml

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

    <!-- SharedPreferences Keys -->
    <string name="sp_key_show_bold_text">showBoldText</string>
    <string name="sp_key_user_name">userName</string>
    <string name="sp_key_show_red_text_color">showRedTextColor</string>
</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.graphics.Typeface;
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");
        boolean showBoldText = mSharedPreferences.getBoolean(getString(R.string.sp_key_show_bold_text), false);
        boolean showRedTextColor = mSharedPreferences.getBoolean(getString(R.string.sp_key_show_red_text_color),false);

        // If user preferred to show bold txt then make it bold
        if(showBoldText){
            mTextView.setTypeface(null, Typeface.BOLD);
        }else {
            mTextView.setTypeface(null,Typeface.NORMAL);
        }

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

        // Display red color text based on user settings
        if(showRedTextColor){
            mTextView.setTextColor(Color.RED);
        }else {
            mTextView.setTextColor(Color.BLACK);
        }
    }
}
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();
    }
}