Android中Data Binding与Observable模式工作原理及示例疑问
Understanding Android Data Binding's Observable Pattern with Your Example
Great question! Let's walk through exactly how this works with your code to clear up your confusion.
1. How does the TextView detect changes to Student.name?
Here's the step-by-step flow behind the scenes:
- Your
Studentclass extendsBaseObservable, which makes it an observable object capable of notifying listeners when its properties change. - When you set the
Studentinstance viaactivityMainBinding.setStudent(...), the auto-generatedActivityMainBindingclass (built by the Data Binding compiler) registers itself as a listener to yourStudentobject. - Whenever the
nameproperty is updated—either by callingsetName()directly, or through the two-way binding in theEditText—thenotifyPropertyChanged(BR.name)method is triggered. - This notification gets sent to all registered listeners (including the
ActivityMainBindinginstance). - The binding class then re-runs the
getName()method to fetch the updated value, and automatically updates theTextView'stextproperty to match the newname.
The two-way binding on the EditText (@={student.name}) also follows this flow: when you type in the EditText, it automatically calls setName() with the new input, which triggers the same notification to update the TextView in real time.
2. What do @Bindable and notifyPropertyChanged(BR.name) do?
Let's break each component down:
@Bindable Annotation
- This annotation tells the Data Binding compiler two critical things:
- It needs to generate a unique identifier for this property in the auto-generated
BRclass (that's whereBR.namecomes from). - The property linked to this getter method should be observable—meaning the binding system should track changes to it and sync updates with connected UI elements.
- It needs to generate a unique identifier for this property in the auto-generated
- Without
@Bindable, the compiler won't generate theBR.namefield, and the binding system will have no way to recognize this property as observable.
notifyPropertyChanged(BR.name)
- This method is part of the
BaseObservableclass, and its sole job is to broadcast that a specific property has been modified. - When you call it with
BR.name, you're explicitly telling all registered listeners (like theActivityMainBindinginstance) exactly which property was updated. - This triggers the binding system to re-fetch the property's value via the
@Bindablegetter and refresh any UI elements bound to that property (yourTextViewandEditTextin this case).
Think of them as a paired system: @Bindable marks the property as trackable and creates its unique ID, while notifyPropertyChanged uses that ID to announce changes and kick off UI updates.
内容的提问来源于stack exchange,提问作者Nikolas Bozic
相关产品推荐
相关产品推荐

