Migrating preferences to AndroidX

Viewed 1890

I'm trying to migrate my old auto-generated (from the activity gallery in Android Studio) settings activity to AndroidX. Unfortunately, I can't find any info on how to do that. The official docs aren't very helpful, since they assume you already have all the code in place to add your preference fragments and XML.

I tried switching the old PreferenceScreen to the AndroidX one, and PreferenceFragment to PreferenceFragmentCompat, but that only results in a runtime exception.

Does anyone know how to perform such migration?

3 Answers

To answer my own question - it's not worth migrating existing preference activity. It's faster to make an empty one and manually set fragments, as in the docs. Everything seems to be working in such case, and most of previous code is unused.

I had to migrate an existing project to AndroidX.

So I just switched to PreferenceFragmentCompat.

To give you an idea here is some example code:

Java:

public class SettingsFragment extends
        androidx.preference.PreferenceFragmentCompat implements
        androidx.preference.Preference.OnPreferenceClickListener,
        androidx.preference.Preference.OnPreferenceChangeListener {
       // ... your code
}

xml:

<androidx.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    android:key="@string/PREF_SCR_MAIN">

    <androidx.preference.PreferenceCategory
        android:key="@string/PREF_CAT_MAIN"
        android:title="@string/pref_cat_main">

        <androidx.preference.CheckBoxPreference
            android:key="@string/TOUCH_TWICE_TO_EXIT"
            android:summary="@string/pref_sum_touch_twice_to_exit"
            android:title="@string/pref_title_touch_twice_to_exit" />

    </androidx.preference.PreferenceCategory>

</androidx.preference.PreferenceScreen 

Go to the Refactor option in the ribbon of Android Studio. Then click Migrate to AndroidX.

Also, add these two lines in build.properties file:

android.useAndroidX=true
android.enableJetifier=true

These lines will force the classes which aren't moved to AndroidX to migrate while migrating.

Note: Please backup your Project when prompted! If you don't know much about AndroidX, please backup your project and then try it!

Related