A
view tree observer is used to register listeners that can be notified of global
changes in the view tree. Such global events include, but are not limited to,
layout of the whole tree, beginning of the drawing pass, touch mode change....
A ViewTreeObserver should never be instantiated by applications as it is
provided by the views hierarchy. Refer to
View.getViewTreeObserver()
for more information.
从上面的描述中,不难看出,ViewTreeObserver是用来帮助我们监听某些View的某些变化的。
在
ViewTreeObserver
中,包含了以下几个接口:
interface
ViewTreeObserver.OnGlobalFocusChangeListener
interface
ViewTreeObserver.OnGlobalLayoutListener
interface
ViewTreeObserver.OnPreDrawListener
interface
ViewTreeObserver.OnScrollChangedListener
interface
ViewTreeObserver.OnTouchModeChangeListener
本文将测试除
ViewTreeObserver.OnScrollChangedListener
外的四个接口
1.
创建一个
Android
Project
,修改
main.xml
使之如下:
<?
xml
version
=
"1.0"
encoding
=
"utf-8"
?>
<
LinearLayout
xmlns:android
=
"http://schemas.android.com/apk/res/android"
android:id
=
"@+id/full_screen"
android:orientation
=
"vertical"
android:layout_width
=
"fill_parent"
android:layout_height
=
"fill_parent"
>
<
TextView
android:id
=
"@+id/tv_show"
android:layout_width
=
"fill_parent"
android:layout_height
=
"wrap_content"
android:text
=
""
android:textSize
=
"32px"
android:textColor
=
"#FFFF00"
/>
<
EditText
android:id
=
"@+id/ed_enter1"
android:layout_width
=
"fill_parent"
android:layout_height
=
"wrap_content"
android:text
=
""
/>
<
EditText
android:id
=
"@+id/ed_enter2"
android:layout_width
=
"fill_parent"
android:layout_height
=
"wrap_content"
android:text
=
""
/>
<
TextView
android:id
=
"@+id/tv_display"
android:layout_width
=
"fill_parent"
android:layout_height
=
"wrap_content"
android:text
=
""
/>
<
Button
android:id
=
"@+id/button"
android:layout_width
=
"fill_parent"
android:layout_height
=
"wrap_content"
android:text
=
"OK"
/>
</
LinearLayout
>
注意:给
layout
增加一个
id
:
full_screen
2.
Activity
对应的
Java
代码如下:
public
class
ControlViewTreeObserver
extends
Activity
implements
OnClickListener,
ViewTreeObserver.OnTouchModeChangeListener,
//
用于监听
Touch
和非
Touch
模式的转换
ViewTreeObserver.OnGlobalLayoutListener,
//
用于监听布局之类的变化,比如某个空间消失了
ViewTreeObserver.OnPreDrawListener,
//
用于在屏幕上画
View
之前,要做什么额外的工作
ViewTreeObserver.OnGlobalFocusChangeListener
//
用于监听焦点的变化
{
private
TextView
tv_show
;
private
ViewTreeObserver
vto
;
private
View
all
;
private
EditText
ed1
;
private
EditText
ed2
;
private
TextView
tv_display
;
private
Button
button
;
private
boolean
btnClicked
;
@Override
public
void
onCreate(Bundle savedInstanceState)
{
super
.onCreate(savedInstanceState);
setContentView(R.layout.
main
);
-->
- 该日志由 frivolous 于11年前发表在综合分类下,最后更新于 2013年04月04日.
- 转载请注明: AndroidGUI13:ViewTreeObserver的常用技巧 | 学步园 +复制链接