Step #3: Displaying Our Preference Screen

Now, we need some Kotlin code to arrange for that preference XML to get used. The typical approach is to use PreferenceFragmentCompat, which is a fragment class that knows how to work with the rest of the preference system to render the PreferenceScreen, collect preferences from the user, and save the changes.

However, this fragment does not match any of our existing com.commonsware.todo.ui sub-packages. So, right-click over the com.commonsware.todo.ui package in the java/ directory, choose “New” > “Package” from the context menu, fill in com.commonsware.todo.ui.prefs for the package name, and press Enter or Return.

Then, right-click over the new com.commonsware.todo.ui.prefs package in the java/ directory and choose “New” > “Kotlin File/Class” from the context menu. For the name, fill in PrefsFragment, and choose “Class” for the kind. Press Enter or Return to create the class, giving you:

package com.commonsware.todo.ui.prefs

class PrefsFragment {
}

Finally, replace that stub class with:

package com.commonsware.todo.ui.prefs

import android.os.Bundle
import androidx.preference.PreferenceFragmentCompat
import com.commonsware.todo.R

class PrefsFragment : PreferenceFragmentCompat() {
  override fun onCreatePreferences(state: Bundle?, rootKey: String?) {
    setPreferencesFromResource(R.xml.prefs, rootKey)
  }
}

Here, we are creating a subclass of PreferenceFragmentCompat. The only required function is onCreatePreferences(), where our job is to provide the details of the preferences that we wish to collect. For that, we can call setPreferencesFromResource(), indicating that we want to display the PreferenceScreen from res/xml/prefs.xml.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.