简体   繁体   English

获取SettingsActivity的ViewModel(MVVM,Android P)

[英]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 SettingsActivity by means of 如果您选择设置时使用模板在Androdi Studio 3.4中创建项目,则将看到示例应用程序,其中SettingsActivity扩展了AppCompatPreferenceActivity扩展了PreferenceActivity扩展了ListActivity扩展了android.app.Activity ,但不是FragmentActivity ,这对于通过SettingsActivity创建ViewModel来说是必需的

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. 因为ViewModelProviders.of()可能仅接受FragmentActivity作为第一个参数。

Is it possible to create a ViewModel for AppCompatPreferenceActivity or it is the next reincarnation of hell with preferences from Google?! 可以为AppCompatPreferenceActivity创建一个ViewModel还是使用Google的首选项实现地狱的下一个转生?

This template has been completely redone in Android Studio 3.5 to match the Settings documentation : 此模板已在Android Studio 3.5中完全重做,以匹配“ 设置”文档

The recommended way to integrate user configurable settings into your application is to use the AndroidX Preference Library. 将用户可配置设置集成到应用程序中的推荐方法是使用AndroidX首选项库。 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. 该库带有Material主题,可在设备和OS版本之间提供一致的用户体验。

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 . AndroidX首选项库完全不需要您使用PreferenceActivity您会注意到,它直接使用AppCompatActivity ,将首选项放入PreferenceFragmentCompat As AppCompatActivity extends FragmentActivity , you will be able to use ViewModel and other AndroidX APIs without issue. 随着AppCompatActivity扩展FragmentActivity ,您将能够使用ViewModel和其他AndroidX API而不会出现问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM