修复 Android 中用于将按钮与函数链接的数据绑定错误

Fixing data binding errors in Android for linking a button with a function

我有一个测试项目,我想通过 DataBinding Libray 和 add:command.

绑定按钮的按下以触发功能

不幸的是,我遇到了错误:

Found data binding errors.
****/ data binding error ****msg:Could not resolve com.example.ckleineidam.testproject.ViewModel.testButton as an accessor or listener on the attribute.

主要活动:

public class MainActivity extends AppCompatActivity {

    ViewModel mModel;
    ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        mModel = new ViewModel(this);
        binding.setViewModel(mModel);
    }
}

视图模型:

public class ViewModel extends BaseObservable {
    private static final String TAG = "VIEW_MODEL";

    private Context mActivity;

    public ViewModel(Context context) {
        this.mActivity=context;
    }

    public void testButton(){
        Log.i(TAG, "Button Click");
    }
}

activity_main.xml:

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

    <data>
        <variable
            name="ViewModel"
            type="com.example.ckleineidam.testproject.ViewModel" />
    </data>

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

            <TextView
                android:id="@+id/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="title"
                app:layout_constraintTop_toTopOf="parent" />

        <Button
            android:id="@+id/activation_button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Test Button"
            android:background="?android:attr/selectableItemBackground"
            app:command="@{ViewModel.testButton}"    
            app:layout_constraintTop_toBottomOf="@id/title" />
    </android.support.constraint.ConstraintLayout >
</layout>

该代码也是 Github 中的示例项目。

您收到此错误是因为按钮上没有属性 app:command。 如果您尝试实现 onClick 功能,您可以使用 android:onClick="@{ViewModel.testButton}" 并将您的函数签名更改为 void testButton(View view)。 要使用自定义属性,您需要定义一个 binding adapter