Using DataBinding library for binding events

前端 未结 9 729
小鲜肉
小鲜肉 2020-12-05 01:52

I\'m trying to bind events with views in xml using DataBinding Library shipped with Android M. I\'m following examples from Android Developers and implement

9条回答
  •  盖世英雄少女心
    2020-12-05 02:24

    Use this format in your xml:

    android:onClick="@{handlers::onClickFriend}"
    

    Pay attention to the ::, do not worry about the red lines in xml editor, because is currently this is open bug for the Android Studio xml editor.

    Where handlers is your variable from data tag:

    
        
    
    

    and onClickFriend is your method:

    public class MyHandlers {
        public void onClickFriend(View view) {
            Log.i(MyHandlers.class.getSimpleName(),"Now Friend");
        }
    }
    

    ADDED

    For handle onLongClick in xml add this:

    android:onLongClick="@{handlers::onLongClickFriend}"
    

    and add onLongClickFriend method in your ViewModel class:

    public class MyHandlers {
        public boolean onLongClickFriend(View view) {
            Log.i(MyHandlers.class.getSimpleName(),"Long clicked Friend");
            return true;
        }
    }
    

    ADDED

    If you need to show toast message, you can use interface (better variant), or pass context in the MyHandlers class in construction:

    public class MyHandlers {
    
        private Context context;
    
        public MyHandlers(Context context) {
            this.context = context;
        }
    
        public boolean onLongClickFriend(View view) {
            Toast.makeText(context, "On Long Click Listener", Toast.LENGTH_SHORT).show();
            return true;
        }
    }
    

提交回复
热议问题