代码之家  ›  专栏  ›  技术社区  ›  Christian

修复Android中链接按钮和函数的数据绑定错误

  •  0
  • Christian  · 技术社区  · 6 年前

    我有一个测试项目,我想通过数据绑定库绑定一个按钮来触发一个函数 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");
        }
    }
    

    活动\u 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 回复  |  直到 6 年前
        1
  •  2
  •   karandeep singh    6 年前

    由于没有属性,因此出现此错误 app:command 如果您试图实现onClick功能,可以使用 android:onClick="@{ViewModel.testButton}" 并将函数签名改为 void testButton(View view) . 要使用自定义属性,需要定义 binding adapter