Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migrating preferences to AndroidX

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?

like image 755
krojew Avatar asked Oct 16 '22 08:10

krojew


2 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.

like image 97
krojew Avatar answered Nov 02 '22 12:11

krojew


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 
like image 44
Martin Pfeffer Avatar answered Nov 02 '22 11:11

Martin Pfeffer