简体   繁体   English

如何将 Android ViewBinding 用于从现有布局膨胀的自定义视图

[英]How to use Android ViewBinding for custom view which inflates from existing layout

I see there is ViewBinding support for Activity and Fragment.我看到有对 Activity 和 Fragment 的 ViewBinding 支持。 But how about custom view?但是自定义视图呢?

My custom view likes this:我的自定义视图喜欢这样:

class MyView @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0,
        defStyleRes: Int = 0
) : LinearLayout(context, attrs, defStyleAttr, defStyleRes) {

    init {
        inflate(context, R.layout.my_view, this)
    }
}

I try to create ViewBinding but it doesn't work.我尝试创建 ViewBinding 但它不起作用。

    private val binding: MyViewBinding

    init {
        inflate(context, R.layout.my_view, this)
        binding = MyViewBinding.inflate(LayoutInflater.from(context))
    }

Do you have any solution for ViewBinding with custom view?你有自定义视图的 ViewBinding 解决方案吗?

you try replace你尝试替换

   init {
        inflate(context, R.layout.my_view, this)
        binding = MyViewBinding.inflate(LayoutInflater.from(context))
    }

with

   init {
        binding = MyViewBinding.inflate(LayoutInflater.from(context),this, false)
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 什么是访问活动的正确方法/逻辑,该活动会使自定义视图的布局从该视图膨胀? - What is the correct approach / logic to access the activity which inflates a layout with custom view from this view? 如何使用 ViewBinding 使用 XML 布局扩展自定义视图? - How to inflate custom view with XML layout with use of ViewBinding? 如何使用 ViewBinding 从父布局访问视图? - How to access a view from parent layout with ViewBinding? 如何在布局中使用视图绑定和视图模型? - how to use viewbinding with viewmodel in layout? Layout Inflater会膨胀FrameLayout而不是我的自定义视图 - Layout inflater inflates FrameLayout instead of my custom view 如何减少viewBinding的使用,从布局中调用(text,edit)views - How to reduce the use of viewBinding, to call (text,edit)views From layout 当从“其他”布局 XML (即,不是相应的片段 XML)中引用视图 ID 时,如何使用 ViewBinding? - How to use ViewBinding when referencing view IDs from "other" layout XML i.e, not the corresponding Fragment XML? Android-如何布局和使用自定义视图? - Android - How to layout and use a custom View? ViewBinding 无法使用布局文件中的视图 - ViewBinding is not able to use views from the layout file Android:如何使用XML进行自定义视图布局 - Android: how to use XML for custom view layout
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM