Android 如何通过viewModels进行数据绑定

Android 如何通过viewModels进行数据绑定,android,android-databinding,Android,Android Databinding,我尝试使用viewModel扩展库对片段中的数据进行绑定的代码,但在编译时发生的错误表明,viewModels()的方法不能以正常绑定方式使用 // the library androidx.lifecycle:lifecycle-viewmodel-ktx import androidx.fragment.app.viewModels class MyFragment : Fragment() { private val viewModel: MyViewModel by vie

我尝试使用viewModel扩展库对片段中的数据进行绑定的代码,但在编译时发生的错误表明,viewModels()的方法
不能以正常绑定方式使用

// the library androidx.lifecycle:lifecycle-viewmodel-ktx

import androidx.fragment.app.viewModels

class MyFragment : Fragment() {

    private val viewModel: MyViewModel by viewModels()  // I can use viewModelFactory to set the binding. But when change to this way, it can not be compile correctly.

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val binding = FragmentMyBinding.inflate(inflater)
        binding.lifecycleOwner = this
        binding.viewModel = viewModel
    ...
}
错误

ANTLR Tool version 4.5.3 used for code generation does not match the 
current runtime version 4.7.1ANTLR Runtime version 4.5.3 used for parser
compilation does not match the current runtime version 4.7.1ANTLR Tool 
version 4.5.3 used for code generation does not match the current runtime 
version 4.7.1ANTLR Runtime version 4.5.3 used for parser compilation does 
not match the current runtime version 4.7.1 
Cannot find
import com.example.app.databinding.FragmentMyBindingImpl;

onCreateView函数的返回视图应该是数据绑定生成的类的根视图

尝试使用此代码

class MyFragment: Fragment() {

private val viewModel: MyViewModel by viewModels()
lateinit var binding: FragmentMyBinding

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    binding = DataBindingUtil.inflate(inflater, R.layout.fragment_layout, container, false)
    return binding.root
}


override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)

    binding.viewModel = viewModel

}

我想您的片段XML部分中存在一个导致此错误的问题,请确保您的代码在其他地方没有错误,因为有时这种错误可能与此无关。也上传你的XML文件,你的viewModel是否附加到活动生命周期?我使用一个活动和多个片段的交互更改,这个viewModel在一个片段中。我检查了xml文件,它们都与我以前使用viewModelFactory时一样,因此我认为错误发生在
by viewModel()
方法中。