数据绑定按钮onclick无法正常工作

Kob*_*Dev 10 android android-databinding

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>
Run Code Online (Sandbox Code Playgroud)

ActionCallBack.java

这是我在MainActivity中实现的接口

public interface ActionCallback { 
    void onClick(View view);
}
Run Code Online (Sandbox Code Playgroud)

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 *****");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我点击按钮onClick()方法没有被激发时,注意显示在输出中或没有执行任何操作.但是使用onClickListener以传统方式工作

Chi*_*sko 22

我认为您的活动声明中存在错误.无论如何,你仍然没有设置你的回调,因此:

binding.setCallback(this);

要么

binding.setCallback(actionCallback);

  • @Chisko你在编辑问题时不需要解决问题.这样你就可以混淆社区,这让人难以理解. (4认同)