码迷,mamicode.com
首页 > 移动开发 > 详细

android点滴之ViewTreeObserver

时间:2014-08-14 13:36:58      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:android   style   http   color   java   io   strong   ar   

一类的基本概念

这是一个注册监听视图树的观察者(observer),在视图树种全局事件改变时得到通知。这个全局事件不仅还包括整个树的布局,从绘画过程开始,触摸模式的改变等。最常见的用途时通过监听获知什么时候,视图的宽高值确定了,可以获取了,以便更改UI。

二类的主要接口:监听器 

interface ViewTreeObserver.OnGlobalFocusChangeListener 当在一个视图树中的焦点状态发生改变时,所要调用的回调函数的接口类
interface ViewTreeObserver.OnGlobalLayoutListener 当在一个视图树中全局布局发生改变或者视图树中的某个视图的可视状态发生改变时,所要调用的回调函数的接口类
interface ViewTreeObserver.OnPreDrawListener 当一个视图树将要绘制时,所要调用的回调函数的接口类
interface ViewTreeObserver.OnScrollChangedListener 当一个视图树中的一些组件发生滚动时,所要调用的回调函数的接口类
interfaceViewTreeObserver.OnTouchModeChangeListener 当一个视图树的触摸模式发生改变时,所要调用的回调函数的接口类

三代码示例

1.创建监听器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  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.一般在onCreate或者onCreateView中注册监听器
1
2
mViewTreeObserver = getActivity().getWindow().getDecorView().getViewTreeObserver();
        mViewTreeObserver.addOnGlobalLayoutListener(mGlobalLayoutListener);



 

android点滴之ViewTreeObserver,布布扣,bubuko.com

android点滴之ViewTreeObserver

标签:android   style   http   color   java   io   strong   ar   

原文地址:http://www.cnblogs.com/zhongle/p/3912104.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!