DataBindingUtil将布局夸大为空

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

我正在使用Android Jetpack导航组件开发单个活动的应用程序。在其中一个片段上,我利用了内置的数据绑定工具。奇怪的是,即使它仅在一周前运行,但直到今天似乎完全没有理由才完全崩溃。

设置:我用于绑定的片段具有以下布局文件:

<?xml version="1.0" encoding="utf-8"?>
<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>
    </data>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/example_layout_root"
        tools:context=".example.ExampleFragment"
        android:background="@color/main_1"
        >

        ...

    </ScrollView>
</layout>

我已经剥离了主要内容,但是它表明我有一个<layout>元素作为根,同时定义了数据和片段布局部分。

片段代码如下:

class ExamleFragment : Fragment() {

    private val viewModel: ExampleViewModel by sharedViewModel()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        val binding : FragmentExampleBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_example, container, false)
        // This one also does not work
        // val binding = FragmentExampleBinding.inflate(inflater, container, false)
        binding.vm = viewModel
        binding.lifecycleOwner = this

        return binding.root
    }
}

我使用Koin将视图模型注入片段中。当我尝试扩大布局(使用DataBindingUtil或生成的FragmentExampleBinding类)时,它返回为null,并且我得到一个InvalidStateException,因为它不应为null。

我尝试过的:

  • 我曾尝试用inflater.inflate(...)扩大版面工作正常,但那样我就不能使用数据绑定。

  • 我已经尝试从布局描述中删除所有内容,并非绝对必要,它仍然不起作用。

  • 我曾尝试恢复到先前的提交(最早的一次提交具有绑定的工作版本),即使以前曾经工作过,现在不起作用。

  • 我什至重新启动并重置了模拟器,尝试了不同的图像,但是无济于事。

有人遇到过类似的事情吗?该代码在周末真的“崩溃了”,因为我刚刚在上周五进行了测试,并且工作正常。

android android-layout android-fragments android-databinding android-viewmodel
1个回答
0
投票

以这种方式执行

class ExamleFragment:Fragment(){

    private val viewModel: ExampleViewModel by sharedViewModel()
    lateinit binding:FragmentExmaple

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
         binding = DataBindingUtil.inflate(inflater, R.layout.fragment_example, container, false)

        binding.vm = viewModel
        binding.lifecycleOwner = this

        return binding.root
    }
}

请让我在这里粘贴您的错误

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