数据绑定将另一个布局内的布局膨胀

时间:2019-06-24 06:19:24

标签: android data-binding android-livedata android-viewmodel

im试图制作一个支持数据绑定的基础工作表对话框片段类。这是我的课:

abstract class RoundedBottomSheetDialogFragment<VM : BaseViewModel, DB : ViewDataBinding> :
    BottomSheetDialogFragment() {

    abstract val viewModel: VM
    open lateinit var binding: DB

    private fun init(inflater: LayoutInflater, container: ViewGroup?) {
        binding = DataBindingUtil.inflate(inflater, getLayoutRes(), container, true)
    }

    abstract fun getLayoutRes(): Int

    abstract fun configEvents()

    abstract fun bindObservables()

    /**
     *
     *  You need override this method.
     *  And you need to set viewModel to binding: binding.viewModel = viewModel
     *
     */
    abstract fun initBinding()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val parentLayout = inflater.inflate(R.layout.rounded_bottom_sheet, container, false)
        init(inflater, parentLayout.container)
        showDialogAsExpanded()
        return parentLayout
    }

    private fun showDialogAsExpanded() {
        dialog?.setOnShowListener {
            val bottomSheetInternal =
                (dialog as BottomSheetDialog).findViewById<View>(R.id.design_bottom_sheet) ?: return@setOnShowListener
            val behavior = BottomSheetBehavior.from(bottomSheetInternal)
            behavior.state = BottomSheetBehavior.STATE_EXPANDED
            behavior.skipCollapsed = true
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        configEvents()
        bindObservables()
    }
}

如果您看到我在此对话框片段类中夸大了布局,而我想在该布局xml文件中使用数据绑定。 这是我的xml文件的示例:

<layout>
    <data>
        <variable
            name="vm"
            type="com.mobtakerteam.walleto.ui.login.searchcountry.SearchCountryViewModel" />

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">


        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/search_list"
            android:layout_width="match_parent"
            android:layout_height="400dp"
            app:data="@{vm.countries}"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            tools:itemCount="20"
            tools:listitem="@layout/fragment_search_country_row" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

但是问题是它无法在xml布局中工作,我必须手动观察kotlin类内部的实时数据对象,如下所示:

viewModel.countries.observe(this, Observer {
        adapter.submitList(it)
    })

那是什么问题?

1 个答案:

答案 0 :(得分:0)

使用LiveData进行绑定,您必须像这样设置生命周期所有者 binding.lifecycleOwner = this