Android Preference example


Your applications provide settings that allow the user to make change to the applications ' features and behaviors. For example, you allow the user to change the background of an activity, specify whether to receive notification, or change the default path to store downloaded files from remote servers. You should use the Preference APIs provided by Android. It is easy to set up.
A Preference is a single setting. Your application may have multiple Preferences. Each Preference has a key-value pair that the system uses to store the setting in a SharedPreference file. These Preferences are displayed in a list. One item of the list corresponds to one setting. All Preferences can be declared in an xml file in which the PreferenceScreen is the root element. Some commonly used Preferences are CheckboxPreference, EditTextPreference, and ListPreference. The CheckboxPreference is a setting to displays checkbox that can be checked or unchecked. The EditTextPreference has a dialog in which there is an EditText to allow the user to enter or modify existing text. The ListPreference displays a list of items that can be selected. You should remember that a value to be stored in the SharePreferences can be one of the following types: boolean, float, int, long, and String.



Now to have an example application on using Android Preference APIs to provide settings, you create a new project. Then in the res/values/strings.xml file, you define two string-arrays. The first array named "colors " stored a list of descriptive text of three colors: White, Black, and Green. The second array stores the codes in hex format of the colors

<?xml version="1.0" encoding="utf-8"?>

<resources>

   <string name="app_name">AndPreference</string>
   <string name="hello_world">Hello world!</string>
   <string name="action_settings">Settings</string>
<string-array name="colors">
     <item>White</item>
     <item>Black</item>
     <item>Green</item>
                
   </string-array>

<string-array name="colors_values">
     <item>#FFFFFF</item>
     <item>#000000</item>
     <item>#00FF00</item>    
     </string-array>
    
</resources>


Next, in the res/xml file, create a Preference file called apppreferences.xml. In this file, you define three preferences as shown below. In this example, only the ListPreference is implemented to allow the user to change the background color of the main activity. The other Preferences (CheckBoxPreference and EditTextPreference) are displayed, but there is no code written to perform actions on these settings. When you define a Perference, you must specify a value to the android:key attribute. For the ListPreference, the android:entries attribute specifies descriptive text or labels of items and the android: entryValues attribute specifies values of the items. The default value of the ListPreference must be an entry from a list of values that is assigned to the android: entryValues attribute. The summary text displays below the title.

<?xml version="1.0" encoding="utf-8"?>

<PreferenceScreen xmlns:android= "http://schemas.android.com/apk/res/android">   
   <ListPreference
     android:key="pref_color"      android:entries="@array/colors"      android:summary="Set the background color of UI"      android:defaultValue="#FFFFFF"     android:entryValues="@array/colors_values"      android:title="Background" />
   <CheckBoxPreference
     android:key="pref_notification"
     android:title="Notification"
     android:summary="Tick or untick to turn on or off notification"
     android:defaultValue="true" />
   <EditTextPreference
     android:key="pref_savepath"
     android:title="Storage"
     android:summary="Set default download path"
     android:defaultValue="edoc_download" />   
</PreferenceScreen>

In the src folder, you create a class called MyPreference that extends the PreferenceFragment class. In the onCreate() method, you call the addPreferencesFromResource() to inflate the Preference xml file and add the preferences to the current Preference hierarchy. To perform actions when there are changes to the Preferences, you need to implement OnSharedPreferenceChangeListener interface. The code to perform the actions is written in the onSharedPreferenceChanged method.

package com.example.playervideoonly;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;


public class MyPreferences extends PreferenceFragment implements OnSharedPreferenceChangeListener{
Activity activity;
//RelativeLayout layout;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
     activity=getActivity();
     addPreferencesFromResource(R.xml.apppreferences);
     setRetainInstance(true);
   }
   public void onSharedPreferenceChanged(SharedPreferences sp, String key){
if(key.equals("pref_color")){
// Set background color of the activity
((MainActivity)getActivity()).setBGColor(sp.getString(key,""));
}


   }
   public void onResume(){
super.onResume();
// Set background color of the activity
SharedPreferences sp=PreferenceManager.getDefaultSharedPreferences(activity);
((MainActivity)getActivity()).setBGColor(sp.getString("pref_color",""));

// Register OnSharedPreferenceChangeListener
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);

}
   public void onPause(){
   super.onPause();
   // Unregister OnSharedPreferenceChangeListener
   getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
  
   }
}

In the MainActivity class, you will write code to add an instance of the PreferenceFragment as shown below.

package com.example.playervideoonly;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;

public class MainActivity extends Activity{

RelativeLayout layout;

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

setContentView(R.layout.activity_main);
layout=(RelativeLayout)findViewById(R.id.parentlayout);     
   FragmentManager fragmentManager = getFragmentManager();
   MyPreferences myFragment=(MyPreferences)fragmentManager.findFragmentByTag("MyPreferences");
     if(myFragment==null){
     FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
      //add a fragment
     myFragment = new MyPreferences();
     fragmentTransaction.add(R.id.parentlayout, myFragment,"MyPreferences");
     fragmentTransaction.commit();
     }
    

}
public void setBGColor(String color){
layout.setBackgroundColor(Color.parseColor(color));

}

}

Before you run the example application, make sure you add the id attribute to the parent layout (android:id="@+id/parentlayout") in the activity_main.xml file.

Android-Preference-example

Posted by: Dara | post date: 04-04-2015 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.