上一篇中给大家介绍了一下自定义View和ViewGroup的流程,并用FlowLayout这个例子给大家演示了一下自定义ViewGroup中onMeasure和onLayout的使用:https://blog.youkuaiyun.com/u013107751/article/details/81701606
今天就写个简单的小例子跟大家一起探讨一下自定义View中的事件处理,我们先来看一下要完成效果:
京东商品详情页大体就是进去的时候展示上面头部商品价格,下单预计送达时间,商品部分评价等等,然后是上滑到底部的时候如果在继续往下滑就滑进商品详情页.根据这个需求,想来想去现有的控件好像都没有能很好解决的,这个时候我们就要考虑使用自定义的ViewGroup了.通过自定义一个ViewGroup然后放入头部一个RecyclerView和一个底部商品详情介绍可以满足该功能:
public class DragSlideLayout extends ViewGroup {
public DragSlideLayout(Context context) {
this(context, null);
}
public DragSlideLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DragSlideLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec,heightMeasureSpec);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return super.onTouchEvent(event);
}
}
定义一个DragSlideLayout继承ViewGroup,重写onMeasure,onLayout这两个方法是必须重写的,不然子View会显示不出来,onFinishInflate则是在XML加载完成的时候我们用来获取DragSlideLayout里面包含的子View的,onInterceptTouchEvent和onTouchEvent则是用来处理拖动的时候的事件处理的,至于对事件的分发机制还不太熟的童鞋可以先移步:https://mp.youkuaiyun.com/postedit/81667157 这边看一下ViewGroup的事件分发机制,这边不做过多的详解.
接下来我们先运用在XML中:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#fff">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="商品详情页" />
</FrameLayout>
<fun.hxy.com.jddragslidelayout.DragSlideLayout
android:id="@+id/tbl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<