自定义Viewgroup拦截事件例子

来源:互联网 发布:软件企业成本核算方法 编辑:程序博客网 时间:2024/05/21 17:36

源代码下载:http://download.csdn.net/detail/fengyun703/9424946

自定义一个ViewGroup,其中包含3个子listview,拖拽中间listview的上部的时候,3个listview一起运动。

1、编写ativity的layout的xml文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    <com.example.mylistviewtest.MyListViews
        android:id="@+id/mylvs"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        <ListView
            android:id="@+id/lv1"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
        <ListView
            android:id="@+id/lv2"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
        <ListView
            android:id="@+id/lv3"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </com.example.mylistviewtest.MyListViews>
</LinearLayout>


2、自定义ViewGroup

public class MyListViews extends ViewGroup

重写MyListview的onLayout方法,在该方法中确定3个listView的位置和大小(为了省事没有重写onMeasure方法了)。

protected void onLayout(boolean changed, int l, int t, int r, int b) {
// System.out.println("开始onLayout   " + l + "  " + t + "  " + r + "   "
// + b);
int width = this.getWidth();
lvWidth = width / 3;
height = this.getHeight();
// System.out.println(width + "    " + lvWidth + "    " + height);


lv1.layout(0, 0, lvWidth, height);
lv2.layout(lvWidth, 0, lvWidth * 2, height);
lv3.layout(lvWidth * 2, 0, lvWidth * 3, height);
}

其中lv1、lv2和lv3在onFinishInflate() 中赋值。

@Override
protected void onFinishInflate() {
lv1 = (ListView) getChildAt(0);
lv2 = (ListView) getChildAt(1);
lv3 = (ListView) getChildAt(2);
}

3、在自定义的Viewgroup中拦截特殊位置(第二个listview的上半部)的事件,重写onInterceptTouchEvent()。

public boolean onInterceptTouchEvent(MotionEvent ev) {
float x = ev.getX();
float y = ev.getY();
int action = ev.getAction();
//
if ((action!=MotionEvent.ACTION_DOWN)&&x > lvWidth && x < 2 * lvWidth && y < (height / 2)) {
//拦截第二个listview的上部touch事件
if (x > lvWidth && x < 2 * lvWidth && y < (height / 2)) {
flag = true; //表示拦截事件
return true;
}
flag = false;//表示不拦截事件
return false;
}

4. 在自定义的Viewgroup中处理拦截事件,重写onTouchEvent。

public boolean onTouchEvent(MotionEvent event) {
//System.out.println("onTouchEvent"+event.getAction());
if(
flag){        //flag在onInterceptTouchEvent中设置,为true标示拦截事件;为false则不拦截。
lv1.dispatchTouchEvent(event);//事件已经被拦截,调用每个listview的dispatchTouchEvent方法分发拦截的事件
lv2.dispatchTouchEvent(event);
lv3.dispatchTouchEvent(event);
//System.out.println("拦截"+event.getAction());
return true;
}

}


0 0
原创粉丝点击