Weird DataBinding in Android

2019-08-25 17:51发布

问题:

I try to figure out how to work with data binding in Android and met a strange problem. When I put my ViewModel class in some package, generated ActivityMainBinding can't see it and say: error: package ViewModels does not exist. But if I put it in the root package, then trouble disappears. Is it my mistake or some kind of bug?

Code:

activity_main.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<data>
    <variable
        name="DataContext"
        type="com.example.sombrero.bluem.ViewModels.MainViewModel" />
</data>
...

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    MainViewModel mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
    binding.setDataContext(mainViewModel);
}

MainViewModel is just empty class for now.

回答1:

I ran into this as well. Thanks to tynn for answering my question.

According to tynn, it is because we didn't follow the oracle naming conventions for packages. The package name should be all lowercase. Changing "ViewModels" to "viewmodels" fixed it for me.



回答2:

Extend MainViewModel from ViewModel

public class MainViewModel extends ViewModel {

}

Read about LiveData