We are currently migrating to Androidx namespace with our Android app project. However I noticed that not only the namespace seems to have changed. For DialogPreference also some interfaces which were using before are now missing
- new interfaces: https://developer.android.com/reference/androidx/preference/DialogPreference
- old interfaces: https://developer.android.com/reference/kotlin/android/preference/DialogPreference
For example the following methods seem to be missing: onBindDialogView, showDialog, onDialogClosed.
Since we use some of these methods to influence the default behavior of the dialog, it is unclear to me how I should realize this functionality now. For example we are validating the input before closing the dialog, we are saving the value in a database instead of the sharedpreferences and adding some dynamic elements to the dialog.
Has anyone else already encountered this problem and found a solution? Did I miss anything in the documentation? Is there another concept that we can / should use?
It would be possible to use Fragments instead of DialogPreference but for small amounts of content (e.g. a list of tree items, where the user can choose from) this seems to be a lot of overhead for me...
Starting from androidx source files, I've migrated custom classes based on old DialogPreference to new androidx.preference.DialogPreference with the following procedure:
Step 1
The old custom dialog class (e.g. CustomDialogPreference) based on legacy DialogPreference should be split into two separate classes:
Step 2
In the main fragment handling preferences based on PreferenceFragmentCompat the onDisplayPreferenceDialog method should be overridden to show the custom dialog, e.g.:
A little hack for everyone who (like me) do not completely understand how we should combine
androidx.preference.DialogPreference
andandroidx.preference.PreferenceDialogFragmentCompat
:Step 1:
In your
DialogFragment
'sonAttach()
method get the value of your desiredSharedPreference
(get the key either fromnewInstance()
method or just hardcore it inside) and save it as a variable. On the other hand, save your new value inSharedPreference
before closing yourDialogFragment
. By doing so, you have created your "custom Preference".Step 2:
Create empty
androidx.preference.DialogPreference
and use it inside yourPreferenceScreen
. Then combine it with yourDialogFragment
as described in 2nd step by @Livio:By doing so, you will get the same result with only difference that you need to deal with
SharedPreference
yourself inside yourDialogFragment
.