1>main_sub.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">
<data>
<variable
name="user"
type="com.lxk.databindingtest.UserInfo" />
<import type="com.lxk.databindingtest.StarUtils"/>
<variable
name="butt"
type="com.lxk.databindingtest.ButtonClickListener" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="@+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:text="@{StarUtils.getStar(user.star)}"
tools:text="一星" />
<TextView
android:id="@+id/textView"
android:layout_width="46dp"
android:layout_height="19dp"
tools:text="姓名"
android:text="@{user.name}"
app:layout_constraintBottom_toTopOf="@+id/textView2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="加分"
android:onClick="@{butt.likeClick}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
2>main.xml导入main_sub.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">
<data>
<variable
name="userInfo"
type="com.lxk.databindingtest.UserInfo" />
<variable
name="buttClick"
type="com.lxk.databindingtest.ButtonClickListener" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include
layout="@layout/main_sub"
app:user="@{userInfo}"
app:butt="@{buttClick}"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
3>MainActivity
public class MainActivity extends AppCompatActivity {
ActivityMainBinding activityMainBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityMainBinding= DataBindingUtil.setContentView(this,R.layout.activity_main);
UserInfo userInfo=new UserInfo("于振锋",5);
activityMainBinding.setUserInfo(userInfo);
activityMainBinding.setButtClick(new ButtonClickListener(this));
}
}
作者:北京小强户外
链接:https://www.jianshu.com/p/5aae2167078b
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。