335_ViewGroup

来源:互联网 发布:java 获取temp目录 编辑:程序博客网 时间:2024/05/01 16:56




ViewGroup


阅读郭霖大神笔记


博客地址:http://blog.csdn.net/sinyu890807/article/details/9097463




ViewGroup就是View的集合,包含很多子View或者子ViewGroup,
比如LinearLayout或者RelativeLayout都是ViewGroup




一.ViewGroup事件分发流程
来自定义一个类MyLayout,继承LinearLayout
public class MyLayout extends LinearLayout {  
  
    public MyLayout(Context context, AttributeSet attrs) {  
        super(context, attrs);  
    }  
  
}  




打开主布局文件activity_main,加入自定义MyLayout


<com.example.viewgrouptouchevent.MyLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:id="@+id/my_layout"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:orientation="vertical" >  
  
    <Button  
        android:id="@+id/button1"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:text="Button1" />  
  
    <Button  
        android:id="@+id/button2"  
        android:layout_width="match_parent"  
        android:layout_height="wrap_content"  
        android:text="Button2" />  
  
</com.example.viewgrouptouchevent.MyLayout> 




然后注册监听事件


myLayout.setOnTouchListener(new OnTouchListener() {  
    @Override  
    public boolean onTouch(View v, MotionEvent event) {  
        Log.d("TAG", "myLayout on touch");  
        return false;  
    }  
});  
button1.setOnClickListener(new OnClickListener() {  
    @Override  
    public void onClick(View v) {  
        Log.d("TAG", "You clicked button1");  
    }  
});  
button2.setOnClickListener(new OnClickListener() {  
    @Override  
    public void onClick(View v) {  
        Log.d("TAG", "You clicked button2");  
    }  
});  


分别点击一下Button1、Button2和空白区域


打印结果:


button1,button2,onTouch


说明了点击button的时候,没有执行MyLayout的onTouch,
可以说button的click把事件消费掉了,所以事件不会向下传递









0 0