Исправление ошибок привязки данных в Android для связывания кнопки с функцией - PullRequest
0 голосов
/ 20 сентября 2018

У меня есть тестовый проект, в котором я хочу привязать нажатие кнопки для запуска функции через Libre DataBinding и 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.

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>

Код также является примером проекта на Github .

1 Ответ

0 голосов
/ 20 сентября 2018

Вы получаете эту ошибку, потому что на кнопке нет атрибута app:command.Если вы пытаетесь получить функциональность onClick, вы можете использовать android:onClick="@{ViewModel.testButton}" и изменить сигнатуру функции на void testButton(View view).Чтобы использовать пользовательские атрибуты, вам необходимо определить адаптер привязки

...