user2545386
user2545386

Reputation: 457

How can I pass onClickListener to <include> tag?

A layout to be include is like this, child.xml:

 <layout>
       <data>
          <variable
              name="click"
              type="">   <!-- What type should be here? -->
       </data>    

       <LinearLayout>
           <View onClick="@{click}"/>
       </LinearLayout>
    </layout>

To include this, parent.xml:

<layout>
    <data>
       <variable
           name="viewModel"
           type="ViewModel"/>
    </data>
    <LinearLayout>
         <View onClick="()->viewModel.click1()"/>
         <include 
             bind:click="()->viewModel.click2()"/>
             layout="@layout/child"/>
    </LinearLayout>
</layout>

So how can I pass the clickEvent to the child.xml only. Since different parent.xml has different ViewModel, I think I shouldn't pass the viewModel to the child.xml. But I don't know how to pass method to child.xml.

The solution now I'm doing is setOnClickListener in Java File.I doubt if dataBinding can make it easier.

Upvotes: 3

Views: 611

Answers (1)

Khemraj Sharma
Khemraj Sharma

Reputation: 59004

in child.xml

<variable
    name="click"
    type="android.view.View.OnClickListener"/>


<View onClick="@{click}"/>

in parent.xml

<include
    layout="@layout/row"
    app:click="@{()-> viewModel.click2()}"
    />

There can be many ways to pass variables in include tag, read @my answer.

Upvotes: 7

Related Questions