简体   繁体   中英

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

I see there is ViewBinding support for Activity and Fragment. 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.

    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?

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)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM