【发布时间】:2018-01-20 00:33:37
【问题描述】:
我正在学习 Android 中的数据绑定,我有点困惑 Observable 模式的工作原理。
我有一个例子:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityMainBinding activityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
activityMainBinding.setStudent(new Student("Rahul"));
activityMainBinding.executePendingBindings();
}
}
和
public class Student extends BaseObservable {
private String name;
public Student(String rahul) {
name = rahul;
}
@Bindable
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
notifyPropertyChanged(BR.name);
}
}
xml 样式:
<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="student"
type="example.com.password.Student"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.com.password.MainActivity"
android:orientation="vertical">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="@={student.name}"/>
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{student.name}"/>
<Button
android:id="@+id/textViewa"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
我对这里的工作流程有一些疑问:
TextView 如何准确知道 Student.name 何时更改?
getter 方法中的 @Binding 注释和 setter 方法中的 notifyPropertyChanged(BR.name) 有什么作用?
【问题讨论】:
标签: android data-binding observable