1. 添加绑定设置
如上一篇文章(Android - DataBinding)一样,在 build.gradle 中添加
buildFeatures{
dataBinding true
}
2. 添加数据类
添加数据类 User.java :
public class User {
public String userName;
public User(String userName) {
this.userName = userName;
}
}
3. 添加ViewModel
添加 UserViewModel.java :
public class UserViewModel {
private ObservableField<User> userObservableField;
public UserViewModel() {
User user = new User("Jack");
userObservableField = new ObservableField<>();
userObservableField.set(user);
}
public String getUserName(){
return userObservableField.get().userName;
}
public void setUserName(String userName){
Log.d("UserViewModel", "userObservableField: " + userName);
userObservableField.get().userName = userName;
}
}
4. 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">
<data>
<variable
name="userViewModel"
type="com.example.databinding2.UserViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:text="用户名"
android:text="@={userViewModel.userName}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
5. MainActivity.java添加绑定
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
activityMainBinding.setUserViewModel(new UserViewModel());
}
}
6. 运行
输入框输入改变,能看到日志打印的数据也跟着改变了。数据改变的时候,输入框的内容也会改变的,这里没有演示出来。
7. 示例代码
https://gitee.com/jie-xio/android_samples/tree/master/DataBinding/DataBinding2
|