Android-DataBinding源码探究
基本使用
關于DataBinding的使用可以直接參考官網數據綁定庫介紹,此處就直接忽略。本篇主要是闡述DataBinding是如何實現liveData的數據更新到對應xml布局
準備Demo
直接clone如下demo
git clone https://github.com/xiaobaoyihao/AndroidDataBindingDemo.git該樣例就是實現最簡單的DataBinding
綁定類
綁定類是用于訪問布局的變量和視圖,所有綁定類都是繼承ViewDataBinding抽象類的。
demo中引入了數據綁定和視圖綁定,所以系統會為每個布局文件生成一個綁定類。默認情況下,類名稱基于布局文件的名稱,它會轉換為 Pascal 大小寫形式并在末尾添加 Binding 后綴。以本demo中fragment_main.xml為例生成的對應類為 FragmentMainBinding。關于綁定類的使用可以直接參考官網使用文檔
我們以本例中FragmentMainBinding為例進行分析
我們先看MainFragment代碼
class MainFragment : Fragment() {companion object {fun newInstance() = MainFragment()}private lateinit var viewModel: MainViewModelprivate lateinit var mBinding: FragmentMainBindingoverride fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,savedInstanceState: Bundle?): View {mBinding = FragmentMainBinding.inflate(layoutInflater, container, false)return mBinding.root}override fun onActivityCreated(savedInstanceState: Bundle?) {super.onActivityCreated(savedInstanceState)viewModel = ViewModelProvider(this).get(MainViewModel::class.java)mBinding.lifecycleOwner = viewLifecycleOwnermBinding.fvm = viewModel} }MainFragment執行了執行了綁定類的inflate靜態方法返回了綁定類對象,而其中root成員變量就是對應布局文件的根視圖
對應布局
viewModel也非常簡單
class MainViewModel : ViewModel() {var mClickedCount = MutableLiveData(0)fun onClickBtn(view: View) {// mCLickCount++mClickedCount.value = mClickedCount.value?.inc()?: 0} }主要實現就是通過按鈕點擊來實現TextView文本修改;為了有針對性分析,我們以問題形式進行展開分析說明
Q1:FragmentMainBinding.inflate返回了什么?
首先我們從build/data_binding_base_class_source_out目錄下找到這個FragmentMainBinding
可以看到MainFragmentBinding類為抽象類,該類引用了對應布局文件的view(帶有id的)以及在布局文件中聲明的viewModule成員變量和bind、inflate相關方法,我們思路回到inflate方法中
這里面的sMapper類型為androidx.databinding.DataBinderMapperImpl,需要提下每個模塊都有同名的DataBinderMapperImpl,app模塊存在二個同名但路徑不一樣;sMapper可以理解為映射表入口類它引用了appl模塊中DataBinderMapperImp
可以清楚看到DataBinderMapperImpl構造器中調用了addMapper方法;我們繼續看getDataBinder方法
可以看到綁定類的查找是依次遍歷項目中所有DataBinderMapperImpl類來搜查綁定類;那么項目中的所有模塊的DataBinderMapperImpl是如何添加到mapper列表中呢?我們從上圖中看到構造器中調用了addMapper方法
public void addMapper(DataBinderMapper mapper) {Class<? extends DataBinderMapper> mapperClass = mapper.getClass();if (mExistingMappers.add(mapperClass)) {mMappers.add(mapper);final List<DataBinderMapper> dependencies = mapper.collectDependencies();for(DataBinderMapper dependency : dependencies) {addMapper(dependency);}}}上面代碼可以看到mMappers維護了apk所有依賴的DataBinderMapper映射表;先是添加app模塊的映射表,然后將其依賴的映射表依次添加到mMappers中;本demo中最終調用了com.example.demo.DataBinderMapperImpl.getDataBinder方法
public class DataBinderMapperImpl extends DataBinderMapper {private static final int LAYOUT_FRAGMENTMAIN = 1;static {INTERNAL_LAYOUT_ID_LOOKUP.put(com.example.demo.R.layout.fragment_main, LAYOUT_FRAGMENTMAIN);}public ViewDataBinding getDataBinder(DataBindingComponent component, View view, int layoutId) {// 通過布局資源id以及根view的tag來進行指定綁定類int localizedLayoutId = INTERNAL_LAYOUT_ID_LOOKUP.get(layoutId);if(localizedLayoutId > 0) {final Object tag = view.getTag();if(tag == null) {throw new RuntimeException("view must have a tag");}switch(localizedLayoutId) {case LAYOUT_FRAGMENTMAIN: {if ("layout/fragment_main_0".equals(tag)) {return new FragmentMainBindingImpl(component, view);}throw new IllegalArgumentException("The tag for fragment_main is invalid. Received: " + tag);}}}return null;}}我們反編譯下apk
每個綁定布局的根view的tag都以layout/{layout_xml_name}_int來命名的,綁定類的查找是通過xml布局名稱以及tag為條件
總結下FragmentMainBinding.inflate調用軌跡總結如下
#mermaid-svg-8jAm7lPfYPjkL5cB .label{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);fill:#333;color:#333}#mermaid-svg-8jAm7lPfYPjkL5cB .label text{fill:#333}#mermaid-svg-8jAm7lPfYPjkL5cB .node rect,#mermaid-svg-8jAm7lPfYPjkL5cB .node circle,#mermaid-svg-8jAm7lPfYPjkL5cB .node ellipse,#mermaid-svg-8jAm7lPfYPjkL5cB .node polygon,#mermaid-svg-8jAm7lPfYPjkL5cB .node path{fill:#ECECFF;stroke:#9370db;stroke-width:1px}#mermaid-svg-8jAm7lPfYPjkL5cB .node .label{text-align:center;fill:#333}#mermaid-svg-8jAm7lPfYPjkL5cB .node.clickable{cursor:pointer}#mermaid-svg-8jAm7lPfYPjkL5cB .arrowheadPath{fill:#333}#mermaid-svg-8jAm7lPfYPjkL5cB .edgePath .path{stroke:#333;stroke-width:1.5px}#mermaid-svg-8jAm7lPfYPjkL5cB .flowchart-link{stroke:#333;fill:none}#mermaid-svg-8jAm7lPfYPjkL5cB .edgeLabel{background-color:#e8e8e8;text-align:center}#mermaid-svg-8jAm7lPfYPjkL5cB .edgeLabel rect{opacity:0.9}#mermaid-svg-8jAm7lPfYPjkL5cB .edgeLabel span{color:#333}#mermaid-svg-8jAm7lPfYPjkL5cB .cluster rect{fill:#ffffde;stroke:#aa3;stroke-width:1px}#mermaid-svg-8jAm7lPfYPjkL5cB .cluster text{fill:#333}#mermaid-svg-8jAm7lPfYPjkL5cB div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);font-size:12px;background:#ffffde;border:1px solid #aa3;border-radius:2px;pointer-events:none;z-index:100}#mermaid-svg-8jAm7lPfYPjkL5cB .actor{stroke:#ccf;fill:#ECECFF}#mermaid-svg-8jAm7lPfYPjkL5cB text.actor>tspan{fill:#000;stroke:none}#mermaid-svg-8jAm7lPfYPjkL5cB .actor-line{stroke:grey}#mermaid-svg-8jAm7lPfYPjkL5cB .messageLine0{stroke-width:1.5;stroke-dasharray:none;stroke:#333}#mermaid-svg-8jAm7lPfYPjkL5cB .messageLine1{stroke-width:1.5;stroke-dasharray:2, 2;stroke:#333}#mermaid-svg-8jAm7lPfYPjkL5cB #arrowhead path{fill:#333;stroke:#333}#mermaid-svg-8jAm7lPfYPjkL5cB .sequenceNumber{fill:#fff}#mermaid-svg-8jAm7lPfYPjkL5cB #sequencenumber{fill:#333}#mermaid-svg-8jAm7lPfYPjkL5cB #crosshead path{fill:#333;stroke:#333}#mermaid-svg-8jAm7lPfYPjkL5cB .messageText{fill:#333;stroke:#333}#mermaid-svg-8jAm7lPfYPjkL5cB .labelBox{stroke:#ccf;fill:#ECECFF}#mermaid-svg-8jAm7lPfYPjkL5cB .labelText,#mermaid-svg-8jAm7lPfYPjkL5cB .labelText>tspan{fill:#000;stroke:none}#mermaid-svg-8jAm7lPfYPjkL5cB .loopText,#mermaid-svg-8jAm7lPfYPjkL5cB .loopText>tspan{fill:#000;stroke:none}#mermaid-svg-8jAm7lPfYPjkL5cB .loopLine{stroke-width:2px;stroke-dasharray:2, 2;stroke:#ccf;fill:#ccf}#mermaid-svg-8jAm7lPfYPjkL5cB .note{stroke:#aa3;fill:#fff5ad}#mermaid-svg-8jAm7lPfYPjkL5cB .noteText,#mermaid-svg-8jAm7lPfYPjkL5cB .noteText>tspan{fill:#000;stroke:none}#mermaid-svg-8jAm7lPfYPjkL5cB .activation0{fill:#f4f4f4;stroke:#666}#mermaid-svg-8jAm7lPfYPjkL5cB .activation1{fill:#f4f4f4;stroke:#666}#mermaid-svg-8jAm7lPfYPjkL5cB .activation2{fill:#f4f4f4;stroke:#666}#mermaid-svg-8jAm7lPfYPjkL5cB .mermaid-main-font{font-family:"trebuchet ms", verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-8jAm7lPfYPjkL5cB .section{stroke:none;opacity:0.2}#mermaid-svg-8jAm7lPfYPjkL5cB .section0{fill:rgba(102,102,255,0.49)}#mermaid-svg-8jAm7lPfYPjkL5cB .section2{fill:#fff400}#mermaid-svg-8jAm7lPfYPjkL5cB .section1,#mermaid-svg-8jAm7lPfYPjkL5cB .section3{fill:#fff;opacity:0.2}#mermaid-svg-8jAm7lPfYPjkL5cB .sectionTitle0{fill:#333}#mermaid-svg-8jAm7lPfYPjkL5cB .sectionTitle1{fill:#333}#mermaid-svg-8jAm7lPfYPjkL5cB .sectionTitle2{fill:#333}#mermaid-svg-8jAm7lPfYPjkL5cB .sectionTitle3{fill:#333}#mermaid-svg-8jAm7lPfYPjkL5cB .sectionTitle{text-anchor:start;font-size:11px;text-height:14px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-8jAm7lPfYPjkL5cB .grid .tick{stroke:#d3d3d3;opacity:0.8;shape-rendering:crispEdges}#mermaid-svg-8jAm7lPfYPjkL5cB .grid .tick text{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-8jAm7lPfYPjkL5cB .grid path{stroke-width:0}#mermaid-svg-8jAm7lPfYPjkL5cB .today{fill:none;stroke:red;stroke-width:2px}#mermaid-svg-8jAm7lPfYPjkL5cB .task{stroke-width:2}#mermaid-svg-8jAm7lPfYPjkL5cB .taskText{text-anchor:middle;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-8jAm7lPfYPjkL5cB .taskText:not([font-size]){font-size:11px}#mermaid-svg-8jAm7lPfYPjkL5cB .taskTextOutsideRight{fill:#000;text-anchor:start;font-size:11px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-8jAm7lPfYPjkL5cB .taskTextOutsideLeft{fill:#000;text-anchor:end;font-size:11px}#mermaid-svg-8jAm7lPfYPjkL5cB .task.clickable{cursor:pointer}#mermaid-svg-8jAm7lPfYPjkL5cB .taskText.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-8jAm7lPfYPjkL5cB .taskTextOutsideLeft.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-8jAm7lPfYPjkL5cB .taskTextOutsideRight.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-8jAm7lPfYPjkL5cB .taskText0,#mermaid-svg-8jAm7lPfYPjkL5cB .taskText1,#mermaid-svg-8jAm7lPfYPjkL5cB .taskText2,#mermaid-svg-8jAm7lPfYPjkL5cB .taskText3{fill:#fff}#mermaid-svg-8jAm7lPfYPjkL5cB .task0,#mermaid-svg-8jAm7lPfYPjkL5cB .task1,#mermaid-svg-8jAm7lPfYPjkL5cB .task2,#mermaid-svg-8jAm7lPfYPjkL5cB .task3{fill:#8a90dd;stroke:#534fbc}#mermaid-svg-8jAm7lPfYPjkL5cB .taskTextOutside0,#mermaid-svg-8jAm7lPfYPjkL5cB .taskTextOutside2{fill:#000}#mermaid-svg-8jAm7lPfYPjkL5cB .taskTextOutside1,#mermaid-svg-8jAm7lPfYPjkL5cB .taskTextOutside3{fill:#000}#mermaid-svg-8jAm7lPfYPjkL5cB .active0,#mermaid-svg-8jAm7lPfYPjkL5cB .active1,#mermaid-svg-8jAm7lPfYPjkL5cB .active2,#mermaid-svg-8jAm7lPfYPjkL5cB .active3{fill:#bfc7ff;stroke:#534fbc}#mermaid-svg-8jAm7lPfYPjkL5cB .activeText0,#mermaid-svg-8jAm7lPfYPjkL5cB .activeText1,#mermaid-svg-8jAm7lPfYPjkL5cB .activeText2,#mermaid-svg-8jAm7lPfYPjkL5cB .activeText3{fill:#000 !important}#mermaid-svg-8jAm7lPfYPjkL5cB .done0,#mermaid-svg-8jAm7lPfYPjkL5cB .done1,#mermaid-svg-8jAm7lPfYPjkL5cB .done2,#mermaid-svg-8jAm7lPfYPjkL5cB .done3{stroke:grey;fill:#d3d3d3;stroke-width:2}#mermaid-svg-8jAm7lPfYPjkL5cB .doneText0,#mermaid-svg-8jAm7lPfYPjkL5cB .doneText1,#mermaid-svg-8jAm7lPfYPjkL5cB .doneText2,#mermaid-svg-8jAm7lPfYPjkL5cB .doneText3{fill:#000 !important}#mermaid-svg-8jAm7lPfYPjkL5cB .crit0,#mermaid-svg-8jAm7lPfYPjkL5cB .crit1,#mermaid-svg-8jAm7lPfYPjkL5cB .crit2,#mermaid-svg-8jAm7lPfYPjkL5cB .crit3{stroke:#f88;fill:red;stroke-width:2}#mermaid-svg-8jAm7lPfYPjkL5cB .activeCrit0,#mermaid-svg-8jAm7lPfYPjkL5cB .activeCrit1,#mermaid-svg-8jAm7lPfYPjkL5cB .activeCrit2,#mermaid-svg-8jAm7lPfYPjkL5cB .activeCrit3{stroke:#f88;fill:#bfc7ff;stroke-width:2}#mermaid-svg-8jAm7lPfYPjkL5cB .doneCrit0,#mermaid-svg-8jAm7lPfYPjkL5cB .doneCrit1,#mermaid-svg-8jAm7lPfYPjkL5cB .doneCrit2,#mermaid-svg-8jAm7lPfYPjkL5cB .doneCrit3{stroke:#f88;fill:#d3d3d3;stroke-width:2;cursor:pointer;shape-rendering:crispEdges}#mermaid-svg-8jAm7lPfYPjkL5cB .milestone{transform:rotate(45deg) scale(0.8, 0.8)}#mermaid-svg-8jAm7lPfYPjkL5cB .milestoneText{font-style:italic}#mermaid-svg-8jAm7lPfYPjkL5cB .doneCritText0,#mermaid-svg-8jAm7lPfYPjkL5cB .doneCritText1,#mermaid-svg-8jAm7lPfYPjkL5cB .doneCritText2,#mermaid-svg-8jAm7lPfYPjkL5cB .doneCritText3{fill:#000 !important}#mermaid-svg-8jAm7lPfYPjkL5cB .activeCritText0,#mermaid-svg-8jAm7lPfYPjkL5cB .activeCritText1,#mermaid-svg-8jAm7lPfYPjkL5cB .activeCritText2,#mermaid-svg-8jAm7lPfYPjkL5cB .activeCritText3{fill:#000 !important}#mermaid-svg-8jAm7lPfYPjkL5cB .titleText{text-anchor:middle;font-size:18px;fill:#000;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-8jAm7lPfYPjkL5cB g.classGroup text{fill:#9370db;stroke:none;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);font-size:10px}#mermaid-svg-8jAm7lPfYPjkL5cB g.classGroup text .title{font-weight:bolder}#mermaid-svg-8jAm7lPfYPjkL5cB g.clickable{cursor:pointer}#mermaid-svg-8jAm7lPfYPjkL5cB g.classGroup rect{fill:#ECECFF;stroke:#9370db}#mermaid-svg-8jAm7lPfYPjkL5cB g.classGroup line{stroke:#9370db;stroke-width:1}#mermaid-svg-8jAm7lPfYPjkL5cB .classLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.5}#mermaid-svg-8jAm7lPfYPjkL5cB .classLabel .label{fill:#9370db;font-size:10px}#mermaid-svg-8jAm7lPfYPjkL5cB .relation{stroke:#9370db;stroke-width:1;fill:none}#mermaid-svg-8jAm7lPfYPjkL5cB .dashed-line{stroke-dasharray:3}#mermaid-svg-8jAm7lPfYPjkL5cB #compositionStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-8jAm7lPfYPjkL5cB #compositionEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-8jAm7lPfYPjkL5cB #aggregationStart{fill:#ECECFF;stroke:#9370db;stroke-width:1}#mermaid-svg-8jAm7lPfYPjkL5cB #aggregationEnd{fill:#ECECFF;stroke:#9370db;stroke-width:1}#mermaid-svg-8jAm7lPfYPjkL5cB #dependencyStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-8jAm7lPfYPjkL5cB #dependencyEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-8jAm7lPfYPjkL5cB #extensionStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-8jAm7lPfYPjkL5cB #extensionEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-8jAm7lPfYPjkL5cB .commit-id,#mermaid-svg-8jAm7lPfYPjkL5cB .commit-msg,#mermaid-svg-8jAm7lPfYPjkL5cB .branch-label{fill:lightgrey;color:lightgrey;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-8jAm7lPfYPjkL5cB .pieTitleText{text-anchor:middle;font-size:25px;fill:#000;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-8jAm7lPfYPjkL5cB .slice{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-8jAm7lPfYPjkL5cB g.stateGroup text{fill:#9370db;stroke:none;font-size:10px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-8jAm7lPfYPjkL5cB g.stateGroup text{fill:#9370db;fill:#333;stroke:none;font-size:10px}#mermaid-svg-8jAm7lPfYPjkL5cB g.statediagram-cluster .cluster-label text{fill:#333}#mermaid-svg-8jAm7lPfYPjkL5cB g.stateGroup .state-title{font-weight:bolder;fill:#000}#mermaid-svg-8jAm7lPfYPjkL5cB g.stateGroup rect{fill:#ECECFF;stroke:#9370db}#mermaid-svg-8jAm7lPfYPjkL5cB g.stateGroup line{stroke:#9370db;stroke-width:1}#mermaid-svg-8jAm7lPfYPjkL5cB .transition{stroke:#9370db;stroke-width:1;fill:none}#mermaid-svg-8jAm7lPfYPjkL5cB .stateGroup .composit{fill:white;border-bottom:1px}#mermaid-svg-8jAm7lPfYPjkL5cB .stateGroup .alt-composit{fill:#e0e0e0;border-bottom:1px}#mermaid-svg-8jAm7lPfYPjkL5cB .state-note{stroke:#aa3;fill:#fff5ad}#mermaid-svg-8jAm7lPfYPjkL5cB .state-note text{fill:black;stroke:none;font-size:10px}#mermaid-svg-8jAm7lPfYPjkL5cB .stateLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.7}#mermaid-svg-8jAm7lPfYPjkL5cB .edgeLabel text{fill:#333}#mermaid-svg-8jAm7lPfYPjkL5cB .stateLabel text{fill:#000;font-size:10px;font-weight:bold;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-8jAm7lPfYPjkL5cB .node circle.state-start{fill:black;stroke:black}#mermaid-svg-8jAm7lPfYPjkL5cB .node circle.state-end{fill:black;stroke:white;stroke-width:1.5}#mermaid-svg-8jAm7lPfYPjkL5cB #statediagram-barbEnd{fill:#9370db}#mermaid-svg-8jAm7lPfYPjkL5cB .statediagram-cluster rect{fill:#ECECFF;stroke:#9370db;stroke-width:1px}#mermaid-svg-8jAm7lPfYPjkL5cB .statediagram-cluster rect.outer{rx:5px;ry:5px}#mermaid-svg-8jAm7lPfYPjkL5cB .statediagram-state .divider{stroke:#9370db}#mermaid-svg-8jAm7lPfYPjkL5cB .statediagram-state .title-state{rx:5px;ry:5px}#mermaid-svg-8jAm7lPfYPjkL5cB .statediagram-cluster.statediagram-cluster .inner{fill:white}#mermaid-svg-8jAm7lPfYPjkL5cB .statediagram-cluster.statediagram-cluster-alt .inner{fill:#e0e0e0}#mermaid-svg-8jAm7lPfYPjkL5cB .statediagram-cluster .inner{rx:0;ry:0}#mermaid-svg-8jAm7lPfYPjkL5cB .statediagram-state rect.basic{rx:5px;ry:5px}#mermaid-svg-8jAm7lPfYPjkL5cB .statediagram-state rect.divider{stroke-dasharray:10,10;fill:#efefef}#mermaid-svg-8jAm7lPfYPjkL5cB .note-edge{stroke-dasharray:5}#mermaid-svg-8jAm7lPfYPjkL5cB .statediagram-note rect{fill:#fff5ad;stroke:#aa3;stroke-width:1px;rx:0;ry:0}:root{--mermaid-font-family: '"trebuchet ms", verdana, arial';--mermaid-font-family: "Comic Sans MS", "Comic Sans", cursive}#mermaid-svg-8jAm7lPfYPjkL5cB .error-icon{fill:#522}#mermaid-svg-8jAm7lPfYPjkL5cB .error-text{fill:#522;stroke:#522}#mermaid-svg-8jAm7lPfYPjkL5cB .edge-thickness-normal{stroke-width:2px}#mermaid-svg-8jAm7lPfYPjkL5cB .edge-thickness-thick{stroke-width:3.5px}#mermaid-svg-8jAm7lPfYPjkL5cB .edge-pattern-solid{stroke-dasharray:0}#mermaid-svg-8jAm7lPfYPjkL5cB .edge-pattern-dashed{stroke-dasharray:3}#mermaid-svg-8jAm7lPfYPjkL5cB .edge-pattern-dotted{stroke-dasharray:2}#mermaid-svg-8jAm7lPfYPjkL5cB .marker{fill:#333}#mermaid-svg-8jAm7lPfYPjkL5cB .marker.cross{stroke:#333}:root { --mermaid-font-family: "trebuchet ms", verdana, arial;}#mermaid-svg-8jAm7lPfYPjkL5cB {color: rgba(0, 0, 0, 0.75);font: ;}FragmentMainBindingViewDataBindingDataBindingUtilandroidx.databinding.DataBinderMapperImplcom.example.demo.DataBinderMapperImplinflateinflateInternalinflatebindgetDataBindergetDataBinderFragmentMainBindingViewDataBindingDataBindingUtilandroidx.databinding.DataBinderMapperImplcom.example.demo.DataBinderMapperImpl至此我們明白了FragmentMainBinding.inflate返回的其實是FragmentMainBindingImpl對象而非FragmentMainBinding(抽象類)
Q2:綁定類是如何解析并持有view?
我們先來看下FragmentMainBinding結構
可以清楚看到它持有了布局中的帶id的view,以及vm;所以綁定類就是view和vm的通訊橋梁;view在什么時候解析并被賦值?我們從綁定類的真正實現類FragmentMainBindingImpl入手,先看下構造器
可以看到內部是調用mapBindings方法返回view的數組,然后將該數組的view賦值到綁定類相應的成員變量當中
我們繼續看下mapBindings方法
// ViewDataBinding.java protected static Object[] mapBindings(DataBindingComponent bindingComponent, View root,int numBindings, IncludedLayouts includes, SparseIntArray viewsWithIds) {Object[] bindings = new Object[numBindings];mapBindings(bindingComponent, root, bindings, includes, viewsWithIds, true);return bindings; }private static void mapBindings(DataBindingComponent bindingComponent, View view,Object[] bindings, IncludedLayouts includes, SparseIntArray viewsWithIds,boolean isRoot) {final int indexInIncludes;final ViewDataBinding existingBinding = getBinding(view);if (existingBinding != null) {return;}Object objTag = view.getTag();final String tag = (objTag instanceof String) ? (String) objTag : null;boolean isBound = false;// 如果是根view,則判斷根view的tag是否以layout開頭if (isRoot && tag != null && tag.startsWith("layout")) {final int underscoreIndex = tag.lastIndexOf('_');//解析根view的tag,將view放到數組的指定位置(位置由xml中的tag后綴數字確定)if (underscoreIndex > 0 && isNumeric(tag, underscoreIndex + 1)) {final int index = parseTagInt(tag, underscoreIndex + 1);if (bindings[index] == null) {bindings[index] = view;}// 確定綁定布局文件存在include元素布局所在位置indexInIncludes = includes == null ? -1 : index;isBound = true;} else {indexInIncludes = -1;}} else if (tag != null && tag.startsWith(BINDING_TAG_PREFIX)) {// 如果tag以binding_開頭,說明需要綁定類持有,所以賦值int tagIndex = parseTagInt(tag, BINDING_NUMBER_START);if (bindings[tagIndex] == null) {bindings[tagIndex] = view;}isBound = true;indexInIncludes = includes == null ? -1 : tagIndex;} else {// Not a bound viewindexInIncludes = -1;}if (!isBound) {final int id = view.getId();if (id > 0) {int index;// 如果xml中view聲明了id,綁定類也是需要持有該viewif (viewsWithIds != null && (index = viewsWithIds.get(id, -1)) >= 0 &&bindings[index] == null) {bindings[index] = view;}}}// 下面的依次遞歸遍歷,邏輯和上面類似if (view instanceof ViewGroup) {final ViewGroup viewGroup = (ViewGroup) view;final int count = viewGroup.getChildCount();int minInclude = 0;for (int i = 0; i < count; i++) {final View child = viewGroup.getChildAt(i);boolean isInclude = false;if (indexInIncludes >= 0 && child.getTag() instanceof String) {String childTag = (String) child.getTag();// include布局根view的tag格式:layout/${layout_name}_0if (childTag.endsWith("_0") &&childTag.startsWith("layout") && childTag.indexOf('/') > 0) {// This *could* be an include. Test against the expected includes.int includeIndex = findIncludeIndex(childTag, minInclude,includes, indexInIncludes);if (includeIndex >= 0) {isInclude = true;minInclude = includeIndex + 1;final int index = includes.indexes[indexInIncludes][includeIndex];final int layoutId = includes.layoutIds[indexInIncludes][includeIndex];int lastMatchingIndex = findLastMatching(viewGroup, i);if (lastMatchingIndex == i) {bindings[index] = DataBindingUtil.bind(bindingComponent, child,layoutId);} else {final int includeCount = lastMatchingIndex - i + 1;final View[] included = new View[includeCount];for (int j = 0; j < includeCount; j++) {included[j] = viewGroup.getChildAt(i + j);}bindings[index] = DataBindingUtil.bind(bindingComponent, included,layoutId);i += includeCount - 1;}}}}if (!isInclude) {mapBindings(bindingComponent, child, bindings, includes, viewsWithIds, false);}}}}我們看下apk中fragment_main.xml中view的tag是否是我們預期那樣?
至此我們明白了綁定類是如何解析并持有view,它是通過解析布局中view的tag攜帶的信息存放到數組指定位置中,綁定類構造器就是通過正確讀取該數組view,賦值到綁定類的成員變量中,賦值成功后對于子view擦除tag,對于根view則將綁定類綁定到tag中,后面是對view的重繪了
Q3:VM中點擊事件是如何綁定到視圖當中?
因為綁定類構造器中有視圖重繪,最終調用invalidateAll,其調用鏈路如下
#mermaid-svg-262Mf6NcAeldqJkf .label{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);fill:#333;color:#333}#mermaid-svg-262Mf6NcAeldqJkf .label text{fill:#333}#mermaid-svg-262Mf6NcAeldqJkf .node rect,#mermaid-svg-262Mf6NcAeldqJkf .node circle,#mermaid-svg-262Mf6NcAeldqJkf .node ellipse,#mermaid-svg-262Mf6NcAeldqJkf .node polygon,#mermaid-svg-262Mf6NcAeldqJkf .node path{fill:#ECECFF;stroke:#9370db;stroke-width:1px}#mermaid-svg-262Mf6NcAeldqJkf .node .label{text-align:center;fill:#333}#mermaid-svg-262Mf6NcAeldqJkf .node.clickable{cursor:pointer}#mermaid-svg-262Mf6NcAeldqJkf .arrowheadPath{fill:#333}#mermaid-svg-262Mf6NcAeldqJkf .edgePath .path{stroke:#333;stroke-width:1.5px}#mermaid-svg-262Mf6NcAeldqJkf .flowchart-link{stroke:#333;fill:none}#mermaid-svg-262Mf6NcAeldqJkf .edgeLabel{background-color:#e8e8e8;text-align:center}#mermaid-svg-262Mf6NcAeldqJkf .edgeLabel rect{opacity:0.9}#mermaid-svg-262Mf6NcAeldqJkf .edgeLabel span{color:#333}#mermaid-svg-262Mf6NcAeldqJkf .cluster rect{fill:#ffffde;stroke:#aa3;stroke-width:1px}#mermaid-svg-262Mf6NcAeldqJkf .cluster text{fill:#333}#mermaid-svg-262Mf6NcAeldqJkf div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);font-size:12px;background:#ffffde;border:1px solid #aa3;border-radius:2px;pointer-events:none;z-index:100}#mermaid-svg-262Mf6NcAeldqJkf .actor{stroke:#ccf;fill:#ECECFF}#mermaid-svg-262Mf6NcAeldqJkf text.actor>tspan{fill:#000;stroke:none}#mermaid-svg-262Mf6NcAeldqJkf .actor-line{stroke:grey}#mermaid-svg-262Mf6NcAeldqJkf .messageLine0{stroke-width:1.5;stroke-dasharray:none;stroke:#333}#mermaid-svg-262Mf6NcAeldqJkf .messageLine1{stroke-width:1.5;stroke-dasharray:2, 2;stroke:#333}#mermaid-svg-262Mf6NcAeldqJkf #arrowhead path{fill:#333;stroke:#333}#mermaid-svg-262Mf6NcAeldqJkf .sequenceNumber{fill:#fff}#mermaid-svg-262Mf6NcAeldqJkf #sequencenumber{fill:#333}#mermaid-svg-262Mf6NcAeldqJkf #crosshead path{fill:#333;stroke:#333}#mermaid-svg-262Mf6NcAeldqJkf .messageText{fill:#333;stroke:#333}#mermaid-svg-262Mf6NcAeldqJkf .labelBox{stroke:#ccf;fill:#ECECFF}#mermaid-svg-262Mf6NcAeldqJkf .labelText,#mermaid-svg-262Mf6NcAeldqJkf .labelText>tspan{fill:#000;stroke:none}#mermaid-svg-262Mf6NcAeldqJkf .loopText,#mermaid-svg-262Mf6NcAeldqJkf .loopText>tspan{fill:#000;stroke:none}#mermaid-svg-262Mf6NcAeldqJkf .loopLine{stroke-width:2px;stroke-dasharray:2, 2;stroke:#ccf;fill:#ccf}#mermaid-svg-262Mf6NcAeldqJkf .note{stroke:#aa3;fill:#fff5ad}#mermaid-svg-262Mf6NcAeldqJkf .noteText,#mermaid-svg-262Mf6NcAeldqJkf .noteText>tspan{fill:#000;stroke:none}#mermaid-svg-262Mf6NcAeldqJkf .activation0{fill:#f4f4f4;stroke:#666}#mermaid-svg-262Mf6NcAeldqJkf .activation1{fill:#f4f4f4;stroke:#666}#mermaid-svg-262Mf6NcAeldqJkf .activation2{fill:#f4f4f4;stroke:#666}#mermaid-svg-262Mf6NcAeldqJkf .mermaid-main-font{font-family:"trebuchet ms", verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-262Mf6NcAeldqJkf .section{stroke:none;opacity:0.2}#mermaid-svg-262Mf6NcAeldqJkf .section0{fill:rgba(102,102,255,0.49)}#mermaid-svg-262Mf6NcAeldqJkf .section2{fill:#fff400}#mermaid-svg-262Mf6NcAeldqJkf .section1,#mermaid-svg-262Mf6NcAeldqJkf .section3{fill:#fff;opacity:0.2}#mermaid-svg-262Mf6NcAeldqJkf .sectionTitle0{fill:#333}#mermaid-svg-262Mf6NcAeldqJkf .sectionTitle1{fill:#333}#mermaid-svg-262Mf6NcAeldqJkf .sectionTitle2{fill:#333}#mermaid-svg-262Mf6NcAeldqJkf .sectionTitle3{fill:#333}#mermaid-svg-262Mf6NcAeldqJkf .sectionTitle{text-anchor:start;font-size:11px;text-height:14px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-262Mf6NcAeldqJkf .grid .tick{stroke:#d3d3d3;opacity:0.8;shape-rendering:crispEdges}#mermaid-svg-262Mf6NcAeldqJkf .grid .tick text{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-262Mf6NcAeldqJkf .grid path{stroke-width:0}#mermaid-svg-262Mf6NcAeldqJkf .today{fill:none;stroke:red;stroke-width:2px}#mermaid-svg-262Mf6NcAeldqJkf .task{stroke-width:2}#mermaid-svg-262Mf6NcAeldqJkf .taskText{text-anchor:middle;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-262Mf6NcAeldqJkf .taskText:not([font-size]){font-size:11px}#mermaid-svg-262Mf6NcAeldqJkf .taskTextOutsideRight{fill:#000;text-anchor:start;font-size:11px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-262Mf6NcAeldqJkf .taskTextOutsideLeft{fill:#000;text-anchor:end;font-size:11px}#mermaid-svg-262Mf6NcAeldqJkf .task.clickable{cursor:pointer}#mermaid-svg-262Mf6NcAeldqJkf .taskText.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-262Mf6NcAeldqJkf .taskTextOutsideLeft.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-262Mf6NcAeldqJkf .taskTextOutsideRight.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-262Mf6NcAeldqJkf .taskText0,#mermaid-svg-262Mf6NcAeldqJkf .taskText1,#mermaid-svg-262Mf6NcAeldqJkf .taskText2,#mermaid-svg-262Mf6NcAeldqJkf .taskText3{fill:#fff}#mermaid-svg-262Mf6NcAeldqJkf .task0,#mermaid-svg-262Mf6NcAeldqJkf .task1,#mermaid-svg-262Mf6NcAeldqJkf .task2,#mermaid-svg-262Mf6NcAeldqJkf .task3{fill:#8a90dd;stroke:#534fbc}#mermaid-svg-262Mf6NcAeldqJkf .taskTextOutside0,#mermaid-svg-262Mf6NcAeldqJkf .taskTextOutside2{fill:#000}#mermaid-svg-262Mf6NcAeldqJkf .taskTextOutside1,#mermaid-svg-262Mf6NcAeldqJkf .taskTextOutside3{fill:#000}#mermaid-svg-262Mf6NcAeldqJkf .active0,#mermaid-svg-262Mf6NcAeldqJkf .active1,#mermaid-svg-262Mf6NcAeldqJkf .active2,#mermaid-svg-262Mf6NcAeldqJkf .active3{fill:#bfc7ff;stroke:#534fbc}#mermaid-svg-262Mf6NcAeldqJkf .activeText0,#mermaid-svg-262Mf6NcAeldqJkf .activeText1,#mermaid-svg-262Mf6NcAeldqJkf .activeText2,#mermaid-svg-262Mf6NcAeldqJkf .activeText3{fill:#000 !important}#mermaid-svg-262Mf6NcAeldqJkf .done0,#mermaid-svg-262Mf6NcAeldqJkf .done1,#mermaid-svg-262Mf6NcAeldqJkf .done2,#mermaid-svg-262Mf6NcAeldqJkf .done3{stroke:grey;fill:#d3d3d3;stroke-width:2}#mermaid-svg-262Mf6NcAeldqJkf .doneText0,#mermaid-svg-262Mf6NcAeldqJkf .doneText1,#mermaid-svg-262Mf6NcAeldqJkf .doneText2,#mermaid-svg-262Mf6NcAeldqJkf .doneText3{fill:#000 !important}#mermaid-svg-262Mf6NcAeldqJkf .crit0,#mermaid-svg-262Mf6NcAeldqJkf .crit1,#mermaid-svg-262Mf6NcAeldqJkf .crit2,#mermaid-svg-262Mf6NcAeldqJkf .crit3{stroke:#f88;fill:red;stroke-width:2}#mermaid-svg-262Mf6NcAeldqJkf .activeCrit0,#mermaid-svg-262Mf6NcAeldqJkf .activeCrit1,#mermaid-svg-262Mf6NcAeldqJkf .activeCrit2,#mermaid-svg-262Mf6NcAeldqJkf .activeCrit3{stroke:#f88;fill:#bfc7ff;stroke-width:2}#mermaid-svg-262Mf6NcAeldqJkf .doneCrit0,#mermaid-svg-262Mf6NcAeldqJkf .doneCrit1,#mermaid-svg-262Mf6NcAeldqJkf .doneCrit2,#mermaid-svg-262Mf6NcAeldqJkf .doneCrit3{stroke:#f88;fill:#d3d3d3;stroke-width:2;cursor:pointer;shape-rendering:crispEdges}#mermaid-svg-262Mf6NcAeldqJkf .milestone{transform:rotate(45deg) scale(0.8, 0.8)}#mermaid-svg-262Mf6NcAeldqJkf .milestoneText{font-style:italic}#mermaid-svg-262Mf6NcAeldqJkf .doneCritText0,#mermaid-svg-262Mf6NcAeldqJkf .doneCritText1,#mermaid-svg-262Mf6NcAeldqJkf .doneCritText2,#mermaid-svg-262Mf6NcAeldqJkf .doneCritText3{fill:#000 !important}#mermaid-svg-262Mf6NcAeldqJkf .activeCritText0,#mermaid-svg-262Mf6NcAeldqJkf .activeCritText1,#mermaid-svg-262Mf6NcAeldqJkf .activeCritText2,#mermaid-svg-262Mf6NcAeldqJkf .activeCritText3{fill:#000 !important}#mermaid-svg-262Mf6NcAeldqJkf .titleText{text-anchor:middle;font-size:18px;fill:#000;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-262Mf6NcAeldqJkf g.classGroup text{fill:#9370db;stroke:none;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);font-size:10px}#mermaid-svg-262Mf6NcAeldqJkf g.classGroup text .title{font-weight:bolder}#mermaid-svg-262Mf6NcAeldqJkf g.clickable{cursor:pointer}#mermaid-svg-262Mf6NcAeldqJkf g.classGroup rect{fill:#ECECFF;stroke:#9370db}#mermaid-svg-262Mf6NcAeldqJkf g.classGroup line{stroke:#9370db;stroke-width:1}#mermaid-svg-262Mf6NcAeldqJkf .classLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.5}#mermaid-svg-262Mf6NcAeldqJkf .classLabel .label{fill:#9370db;font-size:10px}#mermaid-svg-262Mf6NcAeldqJkf .relation{stroke:#9370db;stroke-width:1;fill:none}#mermaid-svg-262Mf6NcAeldqJkf .dashed-line{stroke-dasharray:3}#mermaid-svg-262Mf6NcAeldqJkf #compositionStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-262Mf6NcAeldqJkf #compositionEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-262Mf6NcAeldqJkf #aggregationStart{fill:#ECECFF;stroke:#9370db;stroke-width:1}#mermaid-svg-262Mf6NcAeldqJkf #aggregationEnd{fill:#ECECFF;stroke:#9370db;stroke-width:1}#mermaid-svg-262Mf6NcAeldqJkf #dependencyStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-262Mf6NcAeldqJkf #dependencyEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-262Mf6NcAeldqJkf #extensionStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-262Mf6NcAeldqJkf #extensionEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-262Mf6NcAeldqJkf .commit-id,#mermaid-svg-262Mf6NcAeldqJkf .commit-msg,#mermaid-svg-262Mf6NcAeldqJkf .branch-label{fill:lightgrey;color:lightgrey;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-262Mf6NcAeldqJkf .pieTitleText{text-anchor:middle;font-size:25px;fill:#000;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-262Mf6NcAeldqJkf .slice{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-262Mf6NcAeldqJkf g.stateGroup text{fill:#9370db;stroke:none;font-size:10px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-262Mf6NcAeldqJkf g.stateGroup text{fill:#9370db;fill:#333;stroke:none;font-size:10px}#mermaid-svg-262Mf6NcAeldqJkf g.statediagram-cluster .cluster-label text{fill:#333}#mermaid-svg-262Mf6NcAeldqJkf g.stateGroup .state-title{font-weight:bolder;fill:#000}#mermaid-svg-262Mf6NcAeldqJkf g.stateGroup rect{fill:#ECECFF;stroke:#9370db}#mermaid-svg-262Mf6NcAeldqJkf g.stateGroup line{stroke:#9370db;stroke-width:1}#mermaid-svg-262Mf6NcAeldqJkf .transition{stroke:#9370db;stroke-width:1;fill:none}#mermaid-svg-262Mf6NcAeldqJkf .stateGroup .composit{fill:white;border-bottom:1px}#mermaid-svg-262Mf6NcAeldqJkf .stateGroup .alt-composit{fill:#e0e0e0;border-bottom:1px}#mermaid-svg-262Mf6NcAeldqJkf .state-note{stroke:#aa3;fill:#fff5ad}#mermaid-svg-262Mf6NcAeldqJkf .state-note text{fill:black;stroke:none;font-size:10px}#mermaid-svg-262Mf6NcAeldqJkf .stateLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.7}#mermaid-svg-262Mf6NcAeldqJkf .edgeLabel text{fill:#333}#mermaid-svg-262Mf6NcAeldqJkf .stateLabel text{fill:#000;font-size:10px;font-weight:bold;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-262Mf6NcAeldqJkf .node circle.state-start{fill:black;stroke:black}#mermaid-svg-262Mf6NcAeldqJkf .node circle.state-end{fill:black;stroke:white;stroke-width:1.5}#mermaid-svg-262Mf6NcAeldqJkf #statediagram-barbEnd{fill:#9370db}#mermaid-svg-262Mf6NcAeldqJkf .statediagram-cluster rect{fill:#ECECFF;stroke:#9370db;stroke-width:1px}#mermaid-svg-262Mf6NcAeldqJkf .statediagram-cluster rect.outer{rx:5px;ry:5px}#mermaid-svg-262Mf6NcAeldqJkf .statediagram-state .divider{stroke:#9370db}#mermaid-svg-262Mf6NcAeldqJkf .statediagram-state .title-state{rx:5px;ry:5px}#mermaid-svg-262Mf6NcAeldqJkf .statediagram-cluster.statediagram-cluster .inner{fill:white}#mermaid-svg-262Mf6NcAeldqJkf .statediagram-cluster.statediagram-cluster-alt .inner{fill:#e0e0e0}#mermaid-svg-262Mf6NcAeldqJkf .statediagram-cluster .inner{rx:0;ry:0}#mermaid-svg-262Mf6NcAeldqJkf .statediagram-state rect.basic{rx:5px;ry:5px}#mermaid-svg-262Mf6NcAeldqJkf .statediagram-state rect.divider{stroke-dasharray:10,10;fill:#efefef}#mermaid-svg-262Mf6NcAeldqJkf .note-edge{stroke-dasharray:5}#mermaid-svg-262Mf6NcAeldqJkf .statediagram-note rect{fill:#fff5ad;stroke:#aa3;stroke-width:1px;rx:0;ry:0}:root{--mermaid-font-family: '"trebuchet ms", verdana, arial';--mermaid-font-family: "Comic Sans MS", "Comic Sans", cursive}#mermaid-svg-262Mf6NcAeldqJkf .error-icon{fill:#522}#mermaid-svg-262Mf6NcAeldqJkf .error-text{fill:#522;stroke:#522}#mermaid-svg-262Mf6NcAeldqJkf .edge-thickness-normal{stroke-width:2px}#mermaid-svg-262Mf6NcAeldqJkf .edge-thickness-thick{stroke-width:3.5px}#mermaid-svg-262Mf6NcAeldqJkf .edge-pattern-solid{stroke-dasharray:0}#mermaid-svg-262Mf6NcAeldqJkf .edge-pattern-dashed{stroke-dasharray:3}#mermaid-svg-262Mf6NcAeldqJkf .edge-pattern-dotted{stroke-dasharray:2}#mermaid-svg-262Mf6NcAeldqJkf .marker{fill:#333}#mermaid-svg-262Mf6NcAeldqJkf .marker.cross{stroke:#333}:root { --mermaid-font-family: "trebuchet ms", verdana, arial;}#mermaid-svg-262Mf6NcAeldqJkf {color: rgba(0, 0, 0, 0.75);font: ;}invalidateAllrequestRebindmRebindRunnable.runexecutePendingBindingsexecuteBindingsInternalexecuteBindings我們看下executeBindings部分代碼
可以看到執行綁定是會對按鈕進行事件綁定,這個事件監聽器是OnClickListenerImpl
因為布局中引用了vm.onClickBtn方法,所以這個事件監聽器順其自然地持有vm;因此綁定類的點擊事件綁定最終通過一個包裝類來實現事件的傳導來實現的
Q4:LiveData數據變化是如何更新到view上?
要弄清楚這個問題,我們需要先看看MutableLiveData.setValue
// LiveData.java @MainThread protected void setValue(T value) {assertMainThread("setValue");mVersion++;mData = value;dispatchingValue(null);}void dispatchingValue(@Nullable ObserverWrapper initiator) {if (mDispatchingValue) {mDispatchInvalidated = true;return;}mDispatchingValue = true;do {mDispatchInvalidated = false;if (initiator != null) {considerNotify(initiator);initiator = null;} else {for (Iterator<Map.Entry<Observer<? super T>, ObserverWrapper>> iterator =mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {considerNotify(iterator.next().getValue());if (mDispatchInvalidated) {break;}}}} while (mDispatchInvalidated);mDispatchingValue = false; }因為dispatchingValue傳入了null所以最終執行considerNotify通知所有觀察者,我們來看下considerNotify
private void considerNotify(ObserverWrapper observer) {// 如果LiveData處于非活動狀態,不進行通知,當視圖至少是onStarted時才會通知視圖if (!observer.mActive) {return;}// Check latest state b4 dispatch. Maybe it changed state but we didn't get the event yet.//// we still first check observer.active to keep it as the entrance for events. So even if// the observer moved to an active state, if we've not received that event, we better not// notify for a more predictable notification order.if (!observer.shouldBeActive()) {observer.activeStateChanged(false);return;}if (observer.mLastVersion >= mVersion) {return;}observer.mLastVersion = mVersion;observer.mObserver.onChanged((T) mData); }可以看到最終livedata將變化的數據通知給了所有的觀察者的onChanged方法這個方法相信大家都很熟悉了;
這里的觀察者observer.mObserver類型其實為LifecycleBoundObserver,通常我們都是調用liveData.observe方法來進行監聽data變化
@MainThread public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {assertMainThread("observe");if (owner.getLifecycle().getCurrentState() == DESTROYED) {// ignorereturn;}LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);if (existing != null && !existing.isAttachedTo(owner)) {throw new IllegalArgumentException("Cannot add the same observer"+ " with different lifecycles");}if (existing != null) {return;}owner.getLifecycle().addObserver(wrapper);}可以清楚看到observe方法將我們傳入的觀察者包裝成LifecycleBoundObserver對象,它訂閱了Lifecycle所以有了感知生命周期的能力
總結下基本調用軌跡
#mermaid-svg-0twdS00ONHSEnrBe .label{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);fill:#333;color:#333}#mermaid-svg-0twdS00ONHSEnrBe .label text{fill:#333}#mermaid-svg-0twdS00ONHSEnrBe .node rect,#mermaid-svg-0twdS00ONHSEnrBe .node circle,#mermaid-svg-0twdS00ONHSEnrBe .node ellipse,#mermaid-svg-0twdS00ONHSEnrBe .node polygon,#mermaid-svg-0twdS00ONHSEnrBe .node path{fill:#ECECFF;stroke:#9370db;stroke-width:1px}#mermaid-svg-0twdS00ONHSEnrBe .node .label{text-align:center;fill:#333}#mermaid-svg-0twdS00ONHSEnrBe .node.clickable{cursor:pointer}#mermaid-svg-0twdS00ONHSEnrBe .arrowheadPath{fill:#333}#mermaid-svg-0twdS00ONHSEnrBe .edgePath .path{stroke:#333;stroke-width:1.5px}#mermaid-svg-0twdS00ONHSEnrBe .flowchart-link{stroke:#333;fill:none}#mermaid-svg-0twdS00ONHSEnrBe .edgeLabel{background-color:#e8e8e8;text-align:center}#mermaid-svg-0twdS00ONHSEnrBe .edgeLabel rect{opacity:0.9}#mermaid-svg-0twdS00ONHSEnrBe .edgeLabel span{color:#333}#mermaid-svg-0twdS00ONHSEnrBe .cluster rect{fill:#ffffde;stroke:#aa3;stroke-width:1px}#mermaid-svg-0twdS00ONHSEnrBe .cluster text{fill:#333}#mermaid-svg-0twdS00ONHSEnrBe div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);font-size:12px;background:#ffffde;border:1px solid #aa3;border-radius:2px;pointer-events:none;z-index:100}#mermaid-svg-0twdS00ONHSEnrBe .actor{stroke:#ccf;fill:#ECECFF}#mermaid-svg-0twdS00ONHSEnrBe text.actor>tspan{fill:#000;stroke:none}#mermaid-svg-0twdS00ONHSEnrBe .actor-line{stroke:grey}#mermaid-svg-0twdS00ONHSEnrBe .messageLine0{stroke-width:1.5;stroke-dasharray:none;stroke:#333}#mermaid-svg-0twdS00ONHSEnrBe .messageLine1{stroke-width:1.5;stroke-dasharray:2, 2;stroke:#333}#mermaid-svg-0twdS00ONHSEnrBe #arrowhead path{fill:#333;stroke:#333}#mermaid-svg-0twdS00ONHSEnrBe .sequenceNumber{fill:#fff}#mermaid-svg-0twdS00ONHSEnrBe #sequencenumber{fill:#333}#mermaid-svg-0twdS00ONHSEnrBe #crosshead path{fill:#333;stroke:#333}#mermaid-svg-0twdS00ONHSEnrBe .messageText{fill:#333;stroke:#333}#mermaid-svg-0twdS00ONHSEnrBe .labelBox{stroke:#ccf;fill:#ECECFF}#mermaid-svg-0twdS00ONHSEnrBe .labelText,#mermaid-svg-0twdS00ONHSEnrBe .labelText>tspan{fill:#000;stroke:none}#mermaid-svg-0twdS00ONHSEnrBe .loopText,#mermaid-svg-0twdS00ONHSEnrBe .loopText>tspan{fill:#000;stroke:none}#mermaid-svg-0twdS00ONHSEnrBe .loopLine{stroke-width:2px;stroke-dasharray:2, 2;stroke:#ccf;fill:#ccf}#mermaid-svg-0twdS00ONHSEnrBe .note{stroke:#aa3;fill:#fff5ad}#mermaid-svg-0twdS00ONHSEnrBe .noteText,#mermaid-svg-0twdS00ONHSEnrBe .noteText>tspan{fill:#000;stroke:none}#mermaid-svg-0twdS00ONHSEnrBe .activation0{fill:#f4f4f4;stroke:#666}#mermaid-svg-0twdS00ONHSEnrBe .activation1{fill:#f4f4f4;stroke:#666}#mermaid-svg-0twdS00ONHSEnrBe .activation2{fill:#f4f4f4;stroke:#666}#mermaid-svg-0twdS00ONHSEnrBe .mermaid-main-font{font-family:"trebuchet ms", verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-0twdS00ONHSEnrBe .section{stroke:none;opacity:0.2}#mermaid-svg-0twdS00ONHSEnrBe .section0{fill:rgba(102,102,255,0.49)}#mermaid-svg-0twdS00ONHSEnrBe .section2{fill:#fff400}#mermaid-svg-0twdS00ONHSEnrBe .section1,#mermaid-svg-0twdS00ONHSEnrBe .section3{fill:#fff;opacity:0.2}#mermaid-svg-0twdS00ONHSEnrBe .sectionTitle0{fill:#333}#mermaid-svg-0twdS00ONHSEnrBe .sectionTitle1{fill:#333}#mermaid-svg-0twdS00ONHSEnrBe .sectionTitle2{fill:#333}#mermaid-svg-0twdS00ONHSEnrBe .sectionTitle3{fill:#333}#mermaid-svg-0twdS00ONHSEnrBe .sectionTitle{text-anchor:start;font-size:11px;text-height:14px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-0twdS00ONHSEnrBe .grid .tick{stroke:#d3d3d3;opacity:0.8;shape-rendering:crispEdges}#mermaid-svg-0twdS00ONHSEnrBe .grid .tick text{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-0twdS00ONHSEnrBe .grid path{stroke-width:0}#mermaid-svg-0twdS00ONHSEnrBe .today{fill:none;stroke:red;stroke-width:2px}#mermaid-svg-0twdS00ONHSEnrBe .task{stroke-width:2}#mermaid-svg-0twdS00ONHSEnrBe .taskText{text-anchor:middle;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-0twdS00ONHSEnrBe .taskText:not([font-size]){font-size:11px}#mermaid-svg-0twdS00ONHSEnrBe .taskTextOutsideRight{fill:#000;text-anchor:start;font-size:11px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-0twdS00ONHSEnrBe .taskTextOutsideLeft{fill:#000;text-anchor:end;font-size:11px}#mermaid-svg-0twdS00ONHSEnrBe .task.clickable{cursor:pointer}#mermaid-svg-0twdS00ONHSEnrBe .taskText.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-0twdS00ONHSEnrBe .taskTextOutsideLeft.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-0twdS00ONHSEnrBe .taskTextOutsideRight.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-0twdS00ONHSEnrBe .taskText0,#mermaid-svg-0twdS00ONHSEnrBe .taskText1,#mermaid-svg-0twdS00ONHSEnrBe .taskText2,#mermaid-svg-0twdS00ONHSEnrBe .taskText3{fill:#fff}#mermaid-svg-0twdS00ONHSEnrBe .task0,#mermaid-svg-0twdS00ONHSEnrBe .task1,#mermaid-svg-0twdS00ONHSEnrBe .task2,#mermaid-svg-0twdS00ONHSEnrBe .task3{fill:#8a90dd;stroke:#534fbc}#mermaid-svg-0twdS00ONHSEnrBe .taskTextOutside0,#mermaid-svg-0twdS00ONHSEnrBe .taskTextOutside2{fill:#000}#mermaid-svg-0twdS00ONHSEnrBe .taskTextOutside1,#mermaid-svg-0twdS00ONHSEnrBe .taskTextOutside3{fill:#000}#mermaid-svg-0twdS00ONHSEnrBe .active0,#mermaid-svg-0twdS00ONHSEnrBe .active1,#mermaid-svg-0twdS00ONHSEnrBe .active2,#mermaid-svg-0twdS00ONHSEnrBe .active3{fill:#bfc7ff;stroke:#534fbc}#mermaid-svg-0twdS00ONHSEnrBe .activeText0,#mermaid-svg-0twdS00ONHSEnrBe .activeText1,#mermaid-svg-0twdS00ONHSEnrBe .activeText2,#mermaid-svg-0twdS00ONHSEnrBe .activeText3{fill:#000 !important}#mermaid-svg-0twdS00ONHSEnrBe .done0,#mermaid-svg-0twdS00ONHSEnrBe .done1,#mermaid-svg-0twdS00ONHSEnrBe .done2,#mermaid-svg-0twdS00ONHSEnrBe .done3{stroke:grey;fill:#d3d3d3;stroke-width:2}#mermaid-svg-0twdS00ONHSEnrBe .doneText0,#mermaid-svg-0twdS00ONHSEnrBe .doneText1,#mermaid-svg-0twdS00ONHSEnrBe .doneText2,#mermaid-svg-0twdS00ONHSEnrBe .doneText3{fill:#000 !important}#mermaid-svg-0twdS00ONHSEnrBe .crit0,#mermaid-svg-0twdS00ONHSEnrBe .crit1,#mermaid-svg-0twdS00ONHSEnrBe .crit2,#mermaid-svg-0twdS00ONHSEnrBe .crit3{stroke:#f88;fill:red;stroke-width:2}#mermaid-svg-0twdS00ONHSEnrBe .activeCrit0,#mermaid-svg-0twdS00ONHSEnrBe .activeCrit1,#mermaid-svg-0twdS00ONHSEnrBe .activeCrit2,#mermaid-svg-0twdS00ONHSEnrBe .activeCrit3{stroke:#f88;fill:#bfc7ff;stroke-width:2}#mermaid-svg-0twdS00ONHSEnrBe .doneCrit0,#mermaid-svg-0twdS00ONHSEnrBe .doneCrit1,#mermaid-svg-0twdS00ONHSEnrBe .doneCrit2,#mermaid-svg-0twdS00ONHSEnrBe .doneCrit3{stroke:#f88;fill:#d3d3d3;stroke-width:2;cursor:pointer;shape-rendering:crispEdges}#mermaid-svg-0twdS00ONHSEnrBe .milestone{transform:rotate(45deg) scale(0.8, 0.8)}#mermaid-svg-0twdS00ONHSEnrBe .milestoneText{font-style:italic}#mermaid-svg-0twdS00ONHSEnrBe .doneCritText0,#mermaid-svg-0twdS00ONHSEnrBe .doneCritText1,#mermaid-svg-0twdS00ONHSEnrBe .doneCritText2,#mermaid-svg-0twdS00ONHSEnrBe .doneCritText3{fill:#000 !important}#mermaid-svg-0twdS00ONHSEnrBe .activeCritText0,#mermaid-svg-0twdS00ONHSEnrBe .activeCritText1,#mermaid-svg-0twdS00ONHSEnrBe .activeCritText2,#mermaid-svg-0twdS00ONHSEnrBe .activeCritText3{fill:#000 !important}#mermaid-svg-0twdS00ONHSEnrBe .titleText{text-anchor:middle;font-size:18px;fill:#000;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-0twdS00ONHSEnrBe g.classGroup text{fill:#9370db;stroke:none;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);font-size:10px}#mermaid-svg-0twdS00ONHSEnrBe g.classGroup text .title{font-weight:bolder}#mermaid-svg-0twdS00ONHSEnrBe g.clickable{cursor:pointer}#mermaid-svg-0twdS00ONHSEnrBe g.classGroup rect{fill:#ECECFF;stroke:#9370db}#mermaid-svg-0twdS00ONHSEnrBe g.classGroup line{stroke:#9370db;stroke-width:1}#mermaid-svg-0twdS00ONHSEnrBe .classLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.5}#mermaid-svg-0twdS00ONHSEnrBe .classLabel .label{fill:#9370db;font-size:10px}#mermaid-svg-0twdS00ONHSEnrBe .relation{stroke:#9370db;stroke-width:1;fill:none}#mermaid-svg-0twdS00ONHSEnrBe .dashed-line{stroke-dasharray:3}#mermaid-svg-0twdS00ONHSEnrBe #compositionStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-0twdS00ONHSEnrBe #compositionEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-0twdS00ONHSEnrBe #aggregationStart{fill:#ECECFF;stroke:#9370db;stroke-width:1}#mermaid-svg-0twdS00ONHSEnrBe #aggregationEnd{fill:#ECECFF;stroke:#9370db;stroke-width:1}#mermaid-svg-0twdS00ONHSEnrBe #dependencyStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-0twdS00ONHSEnrBe #dependencyEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-0twdS00ONHSEnrBe #extensionStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-0twdS00ONHSEnrBe #extensionEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-0twdS00ONHSEnrBe .commit-id,#mermaid-svg-0twdS00ONHSEnrBe .commit-msg,#mermaid-svg-0twdS00ONHSEnrBe .branch-label{fill:lightgrey;color:lightgrey;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-0twdS00ONHSEnrBe .pieTitleText{text-anchor:middle;font-size:25px;fill:#000;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-0twdS00ONHSEnrBe .slice{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-0twdS00ONHSEnrBe g.stateGroup text{fill:#9370db;stroke:none;font-size:10px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-0twdS00ONHSEnrBe g.stateGroup text{fill:#9370db;fill:#333;stroke:none;font-size:10px}#mermaid-svg-0twdS00ONHSEnrBe g.statediagram-cluster .cluster-label text{fill:#333}#mermaid-svg-0twdS00ONHSEnrBe g.stateGroup .state-title{font-weight:bolder;fill:#000}#mermaid-svg-0twdS00ONHSEnrBe g.stateGroup rect{fill:#ECECFF;stroke:#9370db}#mermaid-svg-0twdS00ONHSEnrBe g.stateGroup line{stroke:#9370db;stroke-width:1}#mermaid-svg-0twdS00ONHSEnrBe .transition{stroke:#9370db;stroke-width:1;fill:none}#mermaid-svg-0twdS00ONHSEnrBe .stateGroup .composit{fill:white;border-bottom:1px}#mermaid-svg-0twdS00ONHSEnrBe .stateGroup .alt-composit{fill:#e0e0e0;border-bottom:1px}#mermaid-svg-0twdS00ONHSEnrBe .state-note{stroke:#aa3;fill:#fff5ad}#mermaid-svg-0twdS00ONHSEnrBe .state-note text{fill:black;stroke:none;font-size:10px}#mermaid-svg-0twdS00ONHSEnrBe .stateLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.7}#mermaid-svg-0twdS00ONHSEnrBe .edgeLabel text{fill:#333}#mermaid-svg-0twdS00ONHSEnrBe .stateLabel text{fill:#000;font-size:10px;font-weight:bold;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-0twdS00ONHSEnrBe .node circle.state-start{fill:black;stroke:black}#mermaid-svg-0twdS00ONHSEnrBe .node circle.state-end{fill:black;stroke:white;stroke-width:1.5}#mermaid-svg-0twdS00ONHSEnrBe #statediagram-barbEnd{fill:#9370db}#mermaid-svg-0twdS00ONHSEnrBe .statediagram-cluster rect{fill:#ECECFF;stroke:#9370db;stroke-width:1px}#mermaid-svg-0twdS00ONHSEnrBe .statediagram-cluster rect.outer{rx:5px;ry:5px}#mermaid-svg-0twdS00ONHSEnrBe .statediagram-state .divider{stroke:#9370db}#mermaid-svg-0twdS00ONHSEnrBe .statediagram-state .title-state{rx:5px;ry:5px}#mermaid-svg-0twdS00ONHSEnrBe .statediagram-cluster.statediagram-cluster .inner{fill:white}#mermaid-svg-0twdS00ONHSEnrBe .statediagram-cluster.statediagram-cluster-alt .inner{fill:#e0e0e0}#mermaid-svg-0twdS00ONHSEnrBe .statediagram-cluster .inner{rx:0;ry:0}#mermaid-svg-0twdS00ONHSEnrBe .statediagram-state rect.basic{rx:5px;ry:5px}#mermaid-svg-0twdS00ONHSEnrBe .statediagram-state rect.divider{stroke-dasharray:10,10;fill:#efefef}#mermaid-svg-0twdS00ONHSEnrBe .note-edge{stroke-dasharray:5}#mermaid-svg-0twdS00ONHSEnrBe .statediagram-note rect{fill:#fff5ad;stroke:#aa3;stroke-width:1px;rx:0;ry:0}:root{--mermaid-font-family: '"trebuchet ms", verdana, arial';--mermaid-font-family: "Comic Sans MS", "Comic Sans", cursive}#mermaid-svg-0twdS00ONHSEnrBe .error-icon{fill:#522}#mermaid-svg-0twdS00ONHSEnrBe .error-text{fill:#522;stroke:#522}#mermaid-svg-0twdS00ONHSEnrBe .edge-thickness-normal{stroke-width:2px}#mermaid-svg-0twdS00ONHSEnrBe .edge-thickness-thick{stroke-width:3.5px}#mermaid-svg-0twdS00ONHSEnrBe .edge-pattern-solid{stroke-dasharray:0}#mermaid-svg-0twdS00ONHSEnrBe .edge-pattern-dashed{stroke-dasharray:3}#mermaid-svg-0twdS00ONHSEnrBe .edge-pattern-dotted{stroke-dasharray:2}#mermaid-svg-0twdS00ONHSEnrBe .marker{fill:#333}#mermaid-svg-0twdS00ONHSEnrBe .marker.cross{stroke:#333}:root { --mermaid-font-family: "trebuchet ms", verdana, arial;}#mermaid-svg-0twdS00ONHSEnrBe {color: rgba(0, 0, 0, 0.75);font: ;}LiveDataLifecycleBoundObserver.mObserversetValue(T value)dispatchingValue(null)considerNotifyonChanged(data)LiveDataLifecycleBoundObserver.mObserver到這里我們基本明白了liveData的數據更新是如何通知到所有觀察者了。那么綁定類內部是在什么時機訂閱LiveData呢?我們注意到demo中有這樣一行代碼
class MainFragment : Fragment() {...override fun onActivityCreated(savedInstanceState: Bundle?) {super.onActivityCreated(savedInstanceState)viewModel = ViewModelProvider(this).get(MainViewModel::class.java)//重點代碼mBinding.lifecycleOwner = viewLifecycleOwnermBinding.fvm = viewModel} }注意點:對于fragment中建議使用viewLifecycleOwner賦值給對應綁定類,而對于activity可以直接使用this,因為activity中mLifecycleRegistry其實是通過弱引用持有activity,所以沒有內存泄漏風險
/*** Sets the {@link LifecycleOwner} that should be used for observing changes of* LiveData in this binding. If a {@link LiveData} is in one of the binding expressions* and no LifecycleOwner is set, the LiveData will not be observed and updates to it* will not be propagated to the UI.** @param lifecycleOwner The LifecycleOwner that should be used for observing changes of* LiveData in this binding.*/@MainThreadpublic void setLifecycleOwner(@Nullable LifecycleOwner lifecycleOwner) {if (mLifecycleOwner == lifecycleOwner) {return;}if (mLifecycleOwner != null) {mLifecycleOwner.getLifecycle().removeObserver(mOnStartListener);}mLifecycleOwner = lifecycleOwner;if (lifecycleOwner != null) {if (mOnStartListener == null) {mOnStartListener = new OnStartListener(this);}lifecycleOwner.getLifecycle().addObserver(mOnStartListener);}for (WeakListener<?> weakListener : mLocalFieldObservers) {if (weakListener != null) {weakListener.setLifecycleOwner(lifecycleOwner);}}}方法注釋上寫的比較清楚:因為demo中存在binding表達式,如果不調用該方法會導致livedata數據無法更新到view上
其實從上面代碼可以看到,首次會創建了OnStartListener對象并注冊到lifecycle中,這樣單lifecycle進入ON_START生命周期時會自動進行數據綁定,相關實現見下圖
緊接找為綁定類中所有的表達式變量的觀察者設置lifecycleOwner,這里面的觀察者其實就是LiveDataListener.mListener;從哪里可以看出,這里面有點復雜,
最終調用了LiveDataListener.mListener的setLifecycleOwner、setTarget方法,最終又會調用LiveDataListener的setLifecycleOwner、addListener方法,貼下LiveDataListener
private static class LiveDataListener implements Observer,ObservableReference<LiveData<?>> {final WeakListener<LiveData<?>> mListener;LifecycleOwner mLifecycleOwner;public LiveDataListener(ViewDataBinding binder, int localFieldId) {mListener = new WeakListener(binder, localFieldId, this);}@Overridepublic void setLifecycleOwner(LifecycleOwner lifecycleOwner) {// 主要是卸載,重新注冊二個功能LifecycleOwner owner = (LifecycleOwner) lifecycleOwner;LiveData<?> liveData = mListener.getTarget();if (liveData != null) {if (mLifecycleOwner != null) {liveData.removeObserver(this);}if (lifecycleOwner != null) {liveData.observe(owner, this);}}mLifecycleOwner = owner;}@Overridepublic WeakListener<LiveData<?>> getListener() {return mListener;}@Overridepublic void addListener(LiveData<?> target) {if (mLifecycleOwner != null) {// 監聽liveData數據變化target.observe(mLifecycleOwner, this);}}@Overridepublic void removeListener(LiveData<?> target) {target.removeObserver(this);}@Overridepublic void onChanged(@Nullable Object o) {ViewDataBinding binder = mListener.getBinder();if (binder != null) {// 注意此處最后參數為0,這樣后面的onFieldChange返回值必定為true,所以必定會執行requestRebind方法binder.handleFieldChange(mListener.mLocalFieldId, mListener.getTarget(), 0);}}}上述的二個操作完成后,每當livedata變化時都會通知到LiveDataListener.onChanged方法,改方法中會對mDirtyFlags做相關修改,并進行重新調用綁定方法,以實現綁定表達式的更新
// ViewDataBinding.java private void handleFieldChange(int mLocalFieldId, Object object, int fieldId) {if (mInLiveDataRegisterObserver) {// We're in LiveData registration, which always results in a field change// that we can ignore. The value will be read immediately after anyway, so// there is no need to be dirty.return;}// 修改mDirtyFlags位boolean result = onFieldChange(mLocalFieldId, object, fieldId);if (result) {requestRebind();}}requestRebind后會最終又會調用executeBindings這樣就實現了livedata數據變化及時更新到view中;Q4問題比較繞,需要仔細揣摩下,至此Android-DataBindging基本的幾個問題搞清楚了,我們對Andorid-DataBinding有更深入理解,后面的其他延伸的東西都可以觸旁類推了
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的Android-DataBinding源码探究的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android构建流程——篇八
- 下一篇: PresentViewControlle