SlideShare a Scribd company logo
1 of 4
Preference Management
Step1. Create a newAndroidProject.
Step2. Add the followingcode toyouractivityxml file andname itas “main.xml”.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/check_pref_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/view_username_string"
android:textSize="24sp"
android:padding="24dp"
android:gravity="center" >
</Button>
</LinearLayout>
Add“user_prefs_fragment.xml”
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/userPreferenceFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="YourPackagename.ViewAndUpdatePreferencesActivity$UserPr
eferenceFragment"
android:orientation="vertical" >
</fragment>
Addthe followingcode inthe “layout/xml/user_prefs.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:key="@+id/pref_screen" >
<EditTextPreference
android:dialogMessage="Enter Your User Name"
android:dialogTitle="Change User Name"
android:key="uname"
android:negativeButtonText="Cancel"
android:positiveButtonText="Submit"
android:title="User Name"
>
</EditTextPreference>
</PreferenceScreen>
Step3. Add the followingcode intoyour“values.xml file
<string name="view_username_string">View User Name</string>
Step4. Your androidmanifestshouldlike this.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.zaheerabbas.myapplication">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
</uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".PreferencesActivityExample">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ViewAndUpdatePreferencesActivity" >
</activity>
</application>
</manifest>
Step5. Add these twoactivities.
PreferencesActivityExample
public class PreferencesActivityExample extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Open a User Preferences Entry Activity
final Button button = (Button) findViewById(R.id.check_pref_button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(
PreferencesActivityExample.this,
ViewAndUpdatePreferencesActivity.class));
}
});
}
}
ViewAndUpdatePreferencesActivity
public class ViewAndUpdatePreferencesActivity extends Activity {
private static final String USERNAME = "uname";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_prefs_fragment);
}
// Fragment that displays the username preference
public static class UserPreferenceFragment extends PreferenceFragment {
protected static final String TAG = "UserPrefsFragment";
private OnSharedPreferenceChangeListener mListener;
private Preference mUserNamePreference;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.user_prefs);
// Get the username Preference
mUserNamePreference = (Preference) getPreferenceManager()
.findPreference(USERNAME);
// Attach a listener to update summary when username changes
mListener = new OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
mUserNamePreference.setSummary(sharedPreferences.getString(
USERNAME, "None Set"));
}
};
// Get SharedPreferences object managed by the PreferenceManager for
// this Fragment
SharedPreferences prefs = getPreferenceManager()
.getSharedPreferences();
// Register a listener on the SharedPreferences object
prefs.registerOnSharedPreferenceChangeListener(mListener);
// Invoke callback manually to display the current username
mListener.onSharedPreferenceChanged(prefs, USERNAME);
}
}
}
Step7. Done.

More Related Content

What's hot

Support Design Library
Support Design LibrarySupport Design Library
Support Design LibraryTaeho Kim
 
Обзор Android M
Обзор Android MОбзор Android M
Обзор Android MWOX APP
 
Android Design Support Library
Android Design Support LibraryAndroid Design Support Library
Android Design Support LibraryIbnu Sina Wardy
 
12. Android Basic Google Map
12. Android Basic Google Map12. Android Basic Google Map
12. Android Basic Google MapOum Saokosal
 
Get started with watch kit development
Get started with watch kit developmentGet started with watch kit development
Get started with watch kit developmentMindfire Solutions
 
I/O Rewind 2015 : Android Design Support Library
I/O Rewind 2015 : Android Design Support LibraryI/O Rewind 2015 : Android Design Support Library
I/O Rewind 2015 : Android Design Support LibrarySittiphol Phanvilai
 
Developing AIR for Android with Flash Professional CS5
Developing AIR for Android with Flash Professional CS5Developing AIR for Android with Flash Professional CS5
Developing AIR for Android with Flash Professional CS5Chris Griffith
 
Android workshop - 02. Glass development 101
Android workshop - 02. Glass development 101Android workshop - 02. Glass development 101
Android workshop - 02. Glass development 101Johnny Sung
 
21 android2 updated
21 android2 updated21 android2 updated
21 android2 updatedGhanaGTUG
 
Tightly coupled view (model bounded view)
Tightly coupled view (model bounded view)Tightly coupled view (model bounded view)
Tightly coupled view (model bounded view)IT PROGRAMMING WORLD
 
IntelliJ IDEA Plugin Development
IntelliJ IDEA Plugin DevelopmentIntelliJ IDEA Plugin Development
IntelliJ IDEA Plugin DevelopmentAlexander Zaitsev
 
What's new in Android Wear 2.0
What's new in Android Wear 2.0What's new in Android Wear 2.0
What's new in Android Wear 2.0Peter Friese
 
Developing AIR for Android with Flash Professional CS5
Developing AIR for Android with Flash Professional CS5Developing AIR for Android with Flash Professional CS5
Developing AIR for Android with Flash Professional CS5Chris Griffith
 
Being Epic: Best Practices for Android Development
Being Epic: Best Practices for Android DevelopmentBeing Epic: Best Practices for Android Development
Being Epic: Best Practices for Android DevelopmentReto Meier
 

What's hot (20)

Services
ServicesServices
Services
 
Support Design Library
Support Design LibrarySupport Design Library
Support Design Library
 
Icreate
IcreateIcreate
Icreate
 
How to create android push notifications with custom view
How to create android push notifications with custom viewHow to create android push notifications with custom view
How to create android push notifications with custom view
 
Android best practices
Android best practicesAndroid best practices
Android best practices
 
Обзор Android M
Обзор Android MОбзор Android M
Обзор Android M
 
Android Design Support Library
Android Design Support LibraryAndroid Design Support Library
Android Design Support Library
 
12. Android Basic Google Map
12. Android Basic Google Map12. Android Basic Google Map
12. Android Basic Google Map
 
Introduction to Samsung Gear SDK
Introduction to Samsung Gear SDKIntroduction to Samsung Gear SDK
Introduction to Samsung Gear SDK
 
Get started with watch kit development
Get started with watch kit developmentGet started with watch kit development
Get started with watch kit development
 
I/O Rewind 2015 : Android Design Support Library
I/O Rewind 2015 : Android Design Support LibraryI/O Rewind 2015 : Android Design Support Library
I/O Rewind 2015 : Android Design Support Library
 
Developing AIR for Android with Flash Professional CS5
Developing AIR for Android with Flash Professional CS5Developing AIR for Android with Flash Professional CS5
Developing AIR for Android with Flash Professional CS5
 
Android workshop - 02. Glass development 101
Android workshop - 02. Glass development 101Android workshop - 02. Glass development 101
Android workshop - 02. Glass development 101
 
Android Widget
Android WidgetAndroid Widget
Android Widget
 
21 android2 updated
21 android2 updated21 android2 updated
21 android2 updated
 
Tightly coupled view (model bounded view)
Tightly coupled view (model bounded view)Tightly coupled view (model bounded view)
Tightly coupled view (model bounded view)
 
IntelliJ IDEA Plugin Development
IntelliJ IDEA Plugin DevelopmentIntelliJ IDEA Plugin Development
IntelliJ IDEA Plugin Development
 
What's new in Android Wear 2.0
What's new in Android Wear 2.0What's new in Android Wear 2.0
What's new in Android Wear 2.0
 
Developing AIR for Android with Flash Professional CS5
Developing AIR for Android with Flash Professional CS5Developing AIR for Android with Flash Professional CS5
Developing AIR for Android with Flash Professional CS5
 
Being Epic: Best Practices for Android Development
Being Epic: Best Practices for Android DevelopmentBeing Epic: Best Practices for Android Development
Being Epic: Best Practices for Android Development
 

Similar to 4.preference management

3. file external memory
3. file external memory3. file external memory
3. file external memorymaamir farooq
 
01 09 - graphical user interface - basic widgets
01  09 - graphical user interface - basic widgets01  09 - graphical user interface - basic widgets
01 09 - graphical user interface - basic widgetsSiva Kumar reddy Vasipally
 
2. file internal memory
2. file internal memory2. file internal memory
2. file internal memorymaamir farooq
 
Leture5 exercise onactivities
Leture5 exercise onactivitiesLeture5 exercise onactivities
Leture5 exercise onactivitiesmaamir farooq
 
Lecture exercise on activities
Lecture exercise on activitiesLecture exercise on activities
Lecture exercise on activitiesmaamir farooq
 
Android Tutorials : Basic widgets
Android Tutorials : Basic widgetsAndroid Tutorials : Basic widgets
Android Tutorials : Basic widgetsPrajyot Mainkar
 
Lecture #1 Creating your first android project
Lecture #1  Creating your first android projectLecture #1  Creating your first android project
Lecture #1 Creating your first android projectVitali Pekelis
 
Learn Xamarin Absolute Beginners - Permissions, Building the App GUI & Menus
Learn Xamarin Absolute Beginners - Permissions, Building the App GUI & MenusLearn Xamarin Absolute Beginners - Permissions, Building the App GUI & Menus
Learn Xamarin Absolute Beginners - Permissions, Building the App GUI & MenusEng Teong Cheah
 
android layouts
android layoutsandroid layouts
android layoutsDeepa Rani
 
Creation of simple application using - step by step
Creation of simple application using - step by stepCreation of simple application using - step by step
Creation of simple application using - step by steppriya Nithya
 
Printing photos-html-using-android
Printing photos-html-using-androidPrinting photos-html-using-android
Printing photos-html-using-androidKetan Raval
 
Basics and different xml files used in android
Basics and different xml files used in androidBasics and different xml files used in android
Basics and different xml files used in androidMahmudul Hasan
 
How to use data binding in android
How to use data binding in androidHow to use data binding in android
How to use data binding in androidInnovationM
 
Android Workshop
Android WorkshopAndroid Workshop
Android WorkshopJunda Ong
 
Introduction to Android Programming
Introduction to Android ProgrammingIntroduction to Android Programming
Introduction to Android ProgrammingRaveendra R
 
Android Development Made Easy - With Sample Project
Android Development Made Easy - With Sample ProjectAndroid Development Made Easy - With Sample Project
Android Development Made Easy - With Sample ProjectJoemarie Amparo
 
Fragments: Why, How, What For?
Fragments: Why, How, What For?Fragments: Why, How, What For?
Fragments: Why, How, What For?Brenda Cook
 

Similar to 4.preference management (20)

3. file external memory
3. file external memory3. file external memory
3. file external memory
 
1. shared pref
1. shared pref1. shared pref
1. shared pref
 
Android Button
Android ButtonAndroid Button
Android Button
 
01 09 - graphical user interface - basic widgets
01  09 - graphical user interface - basic widgets01  09 - graphical user interface - basic widgets
01 09 - graphical user interface - basic widgets
 
2. file internal memory
2. file internal memory2. file internal memory
2. file internal memory
 
Leture5 exercise onactivities
Leture5 exercise onactivitiesLeture5 exercise onactivities
Leture5 exercise onactivities
 
Lecture exercise on activities
Lecture exercise on activitiesLecture exercise on activities
Lecture exercise on activities
 
Android Tutorials : Basic widgets
Android Tutorials : Basic widgetsAndroid Tutorials : Basic widgets
Android Tutorials : Basic widgets
 
Lecture #1 Creating your first android project
Lecture #1  Creating your first android projectLecture #1  Creating your first android project
Lecture #1 Creating your first android project
 
Learn Xamarin Absolute Beginners - Permissions, Building the App GUI & Menus
Learn Xamarin Absolute Beginners - Permissions, Building the App GUI & MenusLearn Xamarin Absolute Beginners - Permissions, Building the App GUI & Menus
Learn Xamarin Absolute Beginners - Permissions, Building the App GUI & Menus
 
android layouts
android layoutsandroid layouts
android layouts
 
Creation of simple application using - step by step
Creation of simple application using - step by stepCreation of simple application using - step by step
Creation of simple application using - step by step
 
Printing photos-html-using-android
Printing photos-html-using-androidPrinting photos-html-using-android
Printing photos-html-using-android
 
Ap quiz app
Ap quiz appAp quiz app
Ap quiz app
 
Basics and different xml files used in android
Basics and different xml files used in androidBasics and different xml files used in android
Basics and different xml files used in android
 
How to use data binding in android
How to use data binding in androidHow to use data binding in android
How to use data binding in android
 
Android Workshop
Android WorkshopAndroid Workshop
Android Workshop
 
Introduction to Android Programming
Introduction to Android ProgrammingIntroduction to Android Programming
Introduction to Android Programming
 
Android Development Made Easy - With Sample Project
Android Development Made Easy - With Sample ProjectAndroid Development Made Easy - With Sample Project
Android Development Made Easy - With Sample Project
 
Fragments: Why, How, What For?
Fragments: Why, How, What For?Fragments: Why, How, What For?
Fragments: Why, How, What For?
 

More from maamir farooq (20)

Ooad lab1
Ooad lab1Ooad lab1
Ooad lab1
 
Lesson 03
Lesson 03Lesson 03
Lesson 03
 
Lesson 02
Lesson 02Lesson 02
Lesson 02
 
Php client libray
Php client librayPhp client libray
Php client libray
 
Swiftmailer
SwiftmailerSwiftmailer
Swiftmailer
 
Lect15
Lect15Lect15
Lect15
 
Lec 7
Lec 7Lec 7
Lec 7
 
Lec 6
Lec 6Lec 6
Lec 6
 
Lec 5
Lec 5Lec 5
Lec 5
 
J query 1.7 cheat sheet
J query 1.7 cheat sheetJ query 1.7 cheat sheet
J query 1.7 cheat sheet
 
Assignment
AssignmentAssignment
Assignment
 
Java script summary
Java script summaryJava script summary
Java script summary
 
Lec 3
Lec 3Lec 3
Lec 3
 
Lec 2
Lec 2Lec 2
Lec 2
 
Lec 1
Lec 1Lec 1
Lec 1
 
Css summary
Css summaryCss summary
Css summary
 
Manual of image processing lab
Manual of image processing labManual of image processing lab
Manual of image processing lab
 
Session management
Session managementSession management
Session management
 
Data management
Data managementData management
Data management
 
Content provider
Content providerContent provider
Content provider
 

Recently uploaded

Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 

Recently uploaded (20)

Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 

4.preference management

  • 1. Preference Management Step1. Create a newAndroidProject. Step2. Add the followingcode toyouractivityxml file andname itas “main.xml”. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/check_pref_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/view_username_string" android:textSize="24sp" android:padding="24dp" android:gravity="center" > </Button> </LinearLayout> Add“user_prefs_fragment.xml” <?xml version="1.0" encoding="utf-8"?> <fragment xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/userPreferenceFragment" android:layout_width="match_parent" android:layout_height="match_parent" class="YourPackagename.ViewAndUpdatePreferencesActivity$UserPr eferenceFragment" android:orientation="vertical" > </fragment> Addthe followingcode inthe “layout/xml/user_prefs.xml <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" android:key="@+id/pref_screen" > <EditTextPreference android:dialogMessage="Enter Your User Name" android:dialogTitle="Change User Name" android:key="uname" android:negativeButtonText="Cancel" android:positiveButtonText="Submit" android:title="User Name"
  • 2. > </EditTextPreference> </PreferenceScreen> Step3. Add the followingcode intoyour“values.xml file <string name="view_username_string">View User Name</string> Step4. Your androidmanifestshouldlike this. <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.zaheerabbas.myapplication"> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" > </uses-permission> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".PreferencesActivityExample"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".ViewAndUpdatePreferencesActivity" > </activity> </application> </manifest> Step5. Add these twoactivities. PreferencesActivityExample public class PreferencesActivityExample extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Open a User Preferences Entry Activity
  • 3. final Button button = (Button) findViewById(R.id.check_pref_button); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent( PreferencesActivityExample.this, ViewAndUpdatePreferencesActivity.class)); } }); } } ViewAndUpdatePreferencesActivity public class ViewAndUpdatePreferencesActivity extends Activity { private static final String USERNAME = "uname"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.user_prefs_fragment); } // Fragment that displays the username preference public static class UserPreferenceFragment extends PreferenceFragment { protected static final String TAG = "UserPrefsFragment"; private OnSharedPreferenceChangeListener mListener; private Preference mUserNamePreference; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.user_prefs); // Get the username Preference mUserNamePreference = (Preference) getPreferenceManager() .findPreference(USERNAME); // Attach a listener to update summary when username changes mListener = new OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key) { mUserNamePreference.setSummary(sharedPreferences.getString( USERNAME, "None Set")); } }; // Get SharedPreferences object managed by the PreferenceManager for // this Fragment SharedPreferences prefs = getPreferenceManager() .getSharedPreferences();
  • 4. // Register a listener on the SharedPreferences object prefs.registerOnSharedPreferenceChangeListener(mListener); // Invoke callback manually to display the current username mListener.onSharedPreferenceChanged(prefs, USERNAME); } } } Step7. Done.