片段中的Android DataBinding

时间:2019-02-18 02:10:12

标签: android android-fragments kotlin android-databinding

对于布局和片段,我有以下代码:

<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ScanFragment">

        <SurfaceView
            android:id="@+id/cameraPreview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </FrameLayout>
</layout>
class ScanFragment : Fragment() {
    private lateinit var binding: FragmentScanBinding

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
        FragmentScanBinding.inflate(inflater, container, false).also {
            binding = it
        }.root

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        binding.cameraPreview
    }
}

但是,我似乎无法直接从绑定中访问cameraPreview视图。我已经在下面添加了数据绑定的先决条件:

    dataBinding {
        enabled = true
    }

android.databinding.enableV2=true

在gradle.properties内

1 个答案:

答案 0 :(得分:-1)

您应该使用DataBindingUtil

binding = DataBindingUtil.inflate(inflater, R.layout.fragment_scan, container, false) 
return binding.root