Search code examples
androidandroid-databinding

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


I have a test project where I want to bind the press of a button to trigger a function via the DataBinding Libray and add:command.

Unfortunately, I'm getting the error:

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.

MainActivity:

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

ViewModel:

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>

The code is also as an example project at Github.


Solution

  • You are getting this error because there is no attribute app:command on a button. If you are trying to achieve an onClick functionality, you can use android:onClick="@{ViewModel.testButton}" and change your function signature to void testButton(View view). To use custom attributes, you need to define a binding adapter