数据绑定按钮onclick不起作用

databinding button onclick not working

activity_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>
        <import type="android.view.View" />

        <variable
            name="callback"
            type="com.buscom.ActionCallBack" />
    </data>

    <LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/ll_oml"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/grey_50"
        android:orientation="vertical">

        <android.support.design.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="@{(v) -> callback.onClick(v)}"
                android:text="Menu" />
        </android.support.design.widget.CoordinatorLayout>
    </LinearLayout>
</layout>

ActionCallBack.java

这是我在MainActivity中实现的接口

public interface ActionCallback { 
    void onClick(View view);
}

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    actionCallBack = new ActionCallBack() {

        @Override
        public void onClick(View view) {
            System.out.println("Call onclick method *****");
        }
    }
}

当我单击按钮时,未调用 onClick() 方法,输出中显示注释或未执行任何操作。但是它以传统方式与 onClickListener

一起工作

我认为您的 Activity 声明有误。无论如何,您仍然没有设置回调,因此:

binding.setCallback(this);

binding.setCallback(actionCallback);

我用这个解决了这个问题:

binding.setHandlers(this);

我在片段中工作。