Breaking News


Saturday, 8 February 2014

Android Example of using PreferenceFragment

In my old post "Preferences and SharedPreferences" describe how to implement PreferenceActivity calling deprecated addPreferencesFromResource() method. PreferenceActivity 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 functionality should now be found in the new PreferenceFragment class.

It's a example of using PreferenceFragment.

Example of PreferenceFragment


New a Android Application Project, AndroidPreferenceFragment, with Build SDK target Android 4.1 (API 16) and Minimum Required Android 3.0 (API 11), BlankActivity with Navigation Type of None.

Create /res/xml/preferences.xml to define our preferences.
<PreferenceScreen
        xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory
            android:title="PreferenceCategory A">

        <CheckBoxPreference
                android:key="checkbox_preference"
                android:title="title_checkbox_preference"
                android:summary="summary_checkbox_preference" />

    </PreferenceCategory>

    <PreferenceCategory
            android:title="PreferenceCategory B">

        <EditTextPreference
                android:key="edittext_preference"
                android:title="title_edittext_preference"
                android:summary="summary_edittext_preference"
                android:dialogTitle="dialog_title_edittext_preference" />

    </PreferenceCategory>

</PreferenceScreen>


Create PrefsFragment.java extends PreferenceFragment to addPreferencesFromResource.
package com.example.androidpreferencefragment;

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

public class PrefsFragment extends PreferenceFragment {

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

}


Create SetPreferenceActivity.java to load PrefsFragment.
package com.example.androidpreferencefragment;

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

public class SetPreferenceActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  
  getFragmentManager().beginTransaction().replace(android.R.id.content,
                new PrefsFragment()).commit();
 }

}


Modify the main layout, /res/layout/activity_main.xml, to show the preference.
<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" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="@dimen/padding_medium"
        android:text="@string/hello_world"
        tools:context=".MainActivity" />
    
    <CheckBox
        android:id="@+id/prefCheckBox"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="CheckBoxPreference" />
    
    <TextView
        android:id="@+id/prefEditText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
        
</LinearLayout>


The main activity, MainActivity.java.
package com.example.androidpreferencefragment;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.TextView;

public class MainActivity extends Activity {
 
 CheckBox prefCheckBox;
 TextView prefEditText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        prefCheckBox = (CheckBox)findViewById(R.id.prefCheckBox);
     prefEditText = (TextView)findViewById(R.id.prefEditText);
     
     loadPref();
    }

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

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {

  /*
   * Because it's onlt ONE option in the menu.
   * In order to make it simple, We always start SetPreferenceActivity
   * without checking.
   */
  
  Intent intent = new Intent();
        intent.setClass(MainActivity.this, SetPreferenceActivity.class);
        startActivityForResult(intent, 0); 
  
        return true;
 }

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // TODO Auto-generated method stub
  //super.onActivityResult(requestCode, resultCode, data);
  
  /*
   * To make it simple, always re-load Preference setting.
   */
  
  loadPref();
 }
    
 private void loadPref(){
  SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
  
  boolean my_checkbox_preference = mySharedPreferences.getBoolean("checkbox_preference", false);
  prefCheckBox.setChecked(my_checkbox_preference);

  String my_edittext_preference = mySharedPreferences.getString("edittext_preference", "");
     prefEditText.setText(my_edittext_preference);

 }
        
}


Finally, modify AndroidManifest.xml to add SetPreferenceActivity.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidpreferencefragment"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".SetPreferenceActivity"
            android:label="@string/title_activity_main" >
        </activity>
    </application>

</manifest>



Share This
Blogger
Facebook
Disqus

comments powered by Disqus

No comments :

Post a Comment

Subscribe
Labels
Popular Posts

Subscribe Via Email

About Us

THIS IS ANDROID AND JAVA FREE TUTORIAL AND ALL PROVIDE SOLUTION IN ANDROID AND JAVA INTERVIEW QUE AND ANS IS AVAILABLE IN MY BLOG AND ANY QUERY PLEASE CONTACT ME GO NOW CONTACT US PAGE.

Total Pageviews

© Android and Java solution All rights reserved | Designed By Fireandroids