Weird DataBinding in Android

蹲街弑〆低调 提交于 2019-12-11 15:17:31

问题


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



来源:https://stackoverflow.com/questions/52395823/weird-databinding-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!