Android

Settings with PreferenceFragment | Android Settings Example

Android settings

Android application often needs settings that allow users to modify preferences in app. The PreferenceFragment and PreferenceFragmentCompat contains a hierarchy of preference objects displayed on screen in a list. These preferences will automatically save to SharedPreferences as the user interacts with them.

 

Creating a Preferences screen in Android isn’t too hard. Just follow these below steps.

  1. Need to create preference layout
  2. Handle preference in PreferenceFragment
  3. Now load the fragment in an activity

 

Add this below code in your app gradle dependency

 

  1.  Create a xml file name it preferences.xml in res/xml folder and add this below code to it
Create a xml file called array.xml under res/values folder and this below code
 

Create a fragment called SettingsFragment. We will handle our preference from this fragment. In this fragment we extend PreferenceFragment to manipulate our settings when user interacts with it. Any changes made to it we can know that if we implement  SharedPreferences.OnSharedPreferenceChangeListener interface …..

Add this below code in SettingsFragment class

 

Add this below code in your activity to show the settings in your app

 

Why we use beginTransaction().replace() method?

FragmentTransaction.replace(R.id.container,fragment) it will remove any fragmentsthat are already in the container and add your new one to the same container.

So if we interact with settings view it will make changes immediately………..

Screen of Settings

 

Settings PreferenceFragment
Settings PreferenceFragment

 

 

 

Leave a Reply

Your email address will not be published.

twenty − one =