数据绑定:不调用onClick方法

Ale*_*lex 1 android-databinding

Android 4.3以上

我试图使用数据绑定。我从这里使用官方文档数据绑定

因此在app / build.gradle中

dataBinding {
        enabled = true
    }
Run Code Online (Sandbox Code Playgroud)

在我的xml布局文件中:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>    
        <variable
            name="handler"
            type="com.myproject.SettingsFragment" />    
    </data>    
    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">    
        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"                >

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <android.support.constraint.ConstraintLayout
                    android:id="@+id/contentContainer"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <android.support.constraint.ConstraintLayout
                        android:id="@+id/contactUsContainer"
                        android:layout_width="match_parent"
                        android:onClick="@{handler::onClickContactUs}">    

                        <TextView
                            android:id="@+id/contactUsTextView"
                            android:layout_width="0dp"
                            android:layout_height="wrap_content"/>    

                    </android.support.constraint.ConstraintLayout>        
                </android.support.constraint.ConstraintLayout>
            </FrameLayout>
        </ScrollView>
    </android.support.constraint.ConstraintLayout>    
</layout>
Run Code Online (Sandbox Code Playgroud)

这是我的片段SettingsFragment.java

public class SettingsFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
         View rootView = inflater.inflate(R.layout.settings, container, false);
        return rootView;
    }

    public void onClickContactUs(View view) {     
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当我单击容器contactUsContainer时onClickContactUs()不会调用该方法。为什么?

Geo*_*unt 6

您遇到了一个常见问题。首先,您必须使用binding inflate()调用使绑定膨胀。其次,必须设置绑定变量:

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
     MyLayoutBinding binding = MyLayoutBinding.inflate(inflater, container, false);
     binding.setHandler(this);
     return binding.getRoot();
}
Run Code Online (Sandbox Code Playgroud)