androidandroid-preferencesandroid-viewmodelandroid-mvvmviewmodelproviders

Getting ViewModel for SettingsActivity (MVVM, Android P)


If you choose template with Settings creating a project in Androdi Studio 3.4, you will see example app with SettingsActivity extending AppCompatPreferenceActivity extending PreferenceActivity extending ListActivity extending android.app.Activity, but not the FragmentActivity which is necessary for creating a ViewModel for SettingsActivityby means of

SettingsViewModel viewModel

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    viewModel = ViewModelProviders.of(this, viewModelFactory).get(SettingsViewModel.class);
}

because of ViewModelProviders.of() may accept only the FragmentActivity as a first argument.

Is it possible to create a ViewModel for AppCompatPreferenceActivity or it is the next reincarnation of hell with preferences from Google?!


Solution

  • This template has been completely redone in Android Studio 3.5 to match the Settings documentation:

    The recommended way to integrate user configurable settings into your application is to use the AndroidX Preference Library. This library manages the user interface and interacts with storage so that you define only the individual settings that the user can configure. The library comes with a Material theme that provides a consistent user experience across devices and OS versions.

    The AndroidX Preferences Library does not require you to use PreferenceActivity at all - you'll note that it uses AppCompatActivity directly, putting preferences into a PreferenceFragmentCompat. As AppCompatActivity extends FragmentActivity, you will be able to use ViewModel and other AndroidX APIs without issue.