Basic concepts of a class
This is an observer (Observer) that registers the listener view tree and is notified when the global event of the view tree is changed. This global event not only includes the entire tree layout, starting with the painting process, changing the touch pattern, and so on. The most common use is when listening to know when a view's wide height value is determined and can be obtained in order to change the UI.
Main interface of the second class: Listener
Interface Viewtreeobserver.onglobalfocuschangelistener the interface class of the callback function to invoke when the focus state in a view tree is changed
Interface Viewtreeobserver.ongloballayoutlistener the interface class of the callback function to invoke when the global layout changes in a view tree or the visual state of a view in the view tree changes
Interface Viewtreeobserver.onpredrawlistener the interface class of the callback function to invoke when a view tree is about to be drawn
Interface Viewtreeobserver.onscrollchangedlistener the interface class of the callback function to invoke when some components in a view tree are scrolled
Interfaceviewtreeobserver.ontouchmodechangelistener the interface class of the callback function to invoke when the touch mode of a view tree has changed
Three code examples
1. Creating listeners
| 1234567891011121314151617181920 |
private final ViewTreeObserver.OnGlobalLayoutListener mGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { int width = -1; int height = -1; try { width = getActivity().getWindow().getDecorView().getWidth(); height = getActivity().getWindow().getDecorView().getHeight(); } catch (Exception e) { // called too early. so, just skip. } if (width != -1 && mGlobalLayoutWidth != width) {//只有当尺寸真正有了数值,即已经确定了,更新UI才有意义 mGlobalLayoutWidth = width; updateUI(); } else if (height != -1 && mGlobalLayoutHeight != height) { mGlobalLayoutHeight = height; updateUI(); } } }; |
2. General registration of listeners in OnCreate or Oncreateview
| 12 |
mViewTreeObserver = getActivity().getWindow().getDecorView().getViewTreeObserver(); mViewTreeObserver.addOnGlobalLayoutListener(mGlobalLayoutListener); |