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