How to set click listener to LinearLayout using data binding

后端 未结 3 616
独厮守ぢ
独厮守ぢ 2021-02-15 12:39

I am currently trying to set a click listener to a LinearLayout view in the .xml layout file using data binding.

I have managed to get it to wo

相关标签:
3条回答
  • 2021-02-15 13:08

    If Invalidate Cache does not work.

    then Rebuild project from Build>Rebuild. Fix errors if any then Rebuild again.

    0 讨论(0)
  • 2021-02-15 13:11

    So everything was set up correctly and the generated bindings file shows the click listener being set up correctly, but for some very odd reason half the bindings were working and the newer ones weren't. By newer ones meaning the LinearLayout and all the attempts around it.

    What solved the problem was a simple cache invalidation and respective restart and voila, the click listener is working perfectly on the LinearLayout. Just remember to set it clickable and focusable and any child views set as not clickable so they don't consume the event before the parent.

    3 entire days around this one, took less than 10 minutes discussing with others here in the comments to remember trying to invalidate the cache of Android Studio, unbelievable of me...

    0 讨论(0)
  • 2021-02-15 13:18

    You can handle any view click event like below. Hope it helps!

    1) Create interface for handle click event like below.

    interface OnClickHandlerInterface {
        void onClick(View view)
    }
    

    2) Implement that click listener in action class as shown below

    class MainActivity implements OnClickHanderInterface{
        @Override
        void OnClick(View view){
    
        }
    }
    

    3) Now bind this interface in XML file.

    <data>
    
        <variable
            name="clickHandler"
            type=".OnClickHandlerInterface" />
    </data>
    

    4) Now register this interface in action class with use of binding object

    mActivityMainBinding.clickHandler = this
    

    5) Now set onClick on any which you want to set click listener. For you it's LinearLayout

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="72dp"
        android:clickable="true"
        android:focusable="true"
        android:onClick="@{(v)-> clickHandler.onClick(v)}"
        android:orientation="vertical">
    </LinearLayout>
    

    6) Now handle click when your linearLayout clicked you can get click on interface which is implemented in action class.

    @Override
    void OnClick(View view){
        switch(view.getId()){
        case R.id.linearLayout:
            // Handler click and do some actions
            break;
        }
    }
    

    6) As mentioned above you can get layout click by data binding. Hope it will work for you.

    Thanks

    Happy Coding!!

    0 讨论(0)
提交回复
热议问题