Android LiveData,无法创建类viewModel的实例

问题描述 投票:0回答:1

按照android给出的示例,我扩展了ViewModel类

public class NameViewModel extends ViewModel {
private MutableLiveData<String> currentName;

public MutableLiveData<String> getCurrentName() {
    if (currentName == null) {
        currentName = new MutableLiveData<String>();
    }
    return currentName;
}}

并且我观察了LiveData对象

public class NameActivity extends AppCompatActivity {

private NameViewModel model;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Other code to setup the activity...

    // Get the ViewModel.
    model = new ViewModelProvider(this).get(NameViewModel.class);

    // Create the observer which updates the UI.
    final Observer<String> nameObserver = new Observer<String>() {
        @Override
        public void onChanged(@Nullable final String newName) {
            // Update the UI, in this case, a TextView.
            nameTextView.setText(newName);
        }
    };

    // Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
    model.getCurrentName().observe(this, nameObserver);
}}

运行此代码将导致无法创建类NameViewModel的实例,在这里我在做什么错?

java android viewmodel android-livedata
1个回答
0
投票

虽然代码似乎没什么问题。

© www.soinside.com 2019 - 2024. All rights reserved.