ViewBinding - how to get binding for included layouts?

后端 未结 4 879
北恋
北恋 2020-12-08 04:15

While working with ViewBinding I come across few not documented cases.

First: How to get binding for included generic view layout parts, main binding see only items

4条回答
  •  -上瘾入骨i
    2020-12-08 04:49

    In case of:

    1. Include with generic layout (not merge node), we need to assign ID to included part, this way in binding we will have access to included sub part
    
    

    This way in your activity code:

    private lateinit var exampleBinding: ActivityExampleBinding  //activity_example.xml layout
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        exampleBinding = ActivityExampleBinding.inflate(layoutInflater)
        setContentView(exampleBinding.root)
        //we will be able to access included layouts view like this
        val includedView: View = exampleBinding.yourId.idOfIncludedView
    //[...]
    }
    
    1. Include with merge block in external layout. We can't add ID to it because merge block is not a view. Let's say we have such eternal merge layout (merge_layout.xm):
    
    
    
        
    
    

    To properly bind such merge layout we need to:

    In your activity code:

    private lateinit var exampleBinding: ActivityExampleBinding  //activity_example.xml layout
    private lateinit var mergeBinding: MergeLayoutBinding  //merge_layout.xml layout
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        exampleBinding = ActivityExampleBinding.inflate(layoutInflater)
        //we need to bind the root layout with our binder for external layout
        mergeBinding = MergeLayoutBinding.bind(exampleBinding.root)
        setContentView(exampleBinding.root)
        //we will be able to access included in merge layout views like this
        val mergedView: View = mergeBinding.someView
    //[...]
    }
    

提交回复
热议问题