PreferenceActivity is deprecated now but it’s a really nice new solution to manage your preferences. I’m gonna show you a simple implementation of PreferenceFragment, how to use it in Activity which you’d like to make a Preference Page and how to get values in your app. Example is about saving booleans and making preference fields clickable to call a method. Obviously you can put a wide variety of preference fields and it will work out of the box. PreferenceFragment makes everything easier, automated and it’s great.
When I started to learn about creating Android Apps, PreferenceActivity was already deprecated so I had an opportunity to learn something up to date. I really recommend that way of making a preference page. It’s more adjustable and complex solution. First thing to do is to create a preference layout. You can notice it’s located in xml directory while all normal layouts are in layout directory. Well, it’s somehow special and deserves its own location. You don’t have one? Just create the directory in your resources.
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceCategory android:title="@string/preference_category1"> <CheckBoxPreference android:key="example_key" android:title="@string/example_key" android:defaultValue="true"/> <CheckBoxPreference android:key="transparent_nav" android:title="@string/transparent_nav" android:summary="@string/transparent_nav_description" android:defaultValue="false"/> </PreferenceCategory> <PreferenceCategory android:title="@string/preference_category2"> <Preference android:key="call_method" android:title="@string/call_method" android:summary="@string/call_method_description"/> </PreferenceCategory> </PreferenceScreen>
I assume you are creating the app using Android Studio. Edit your build.gradle configuration file. While creating this example I used Minimum SDK 14 (Ice Cream Sandwich). Make sure you are using the same value as well to avoid possible errors. PreferenceFragment may not be present in older versions of Android SDK. I’m not sure when it was actually introduced but it’s not so important.
apply plugin: 'com.android.application' android { compileSdkVersion 21 buildToolsVersion "21.1.2" defaultConfig { applicationId "org.indywidualni.preferences" minSdkVersion 14 targetSdkVersion 21 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } productFlavors { } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile 'com.android.support:appcompat-v7:21.0.3' }
Now a bit of real coding. Create a new class and put the code in there. It will create SettingsFragment which you can use later to display a preference page in an Activity of your choice.
Continue reading Shared Preferences, Preference Fragment & transparent Navbar