最简单的Pull-To-Refresh实例

例子是一个原型操作, 所以特殊功能都可以基于此进行添加。
突出两点:
1: UI 布局
onMeasure 处理Header和Content的大小
onLayout 处理Header和Content的位置
实际下拉过程中, 是没有回调onLayout方法。
而是通过 mHeaderView.offsetTopAndBottom(3); 设置偏移位置。
通过invalidate();进行刷新。
PS:
offsetTopAndBottom方法设置View的位置, 不会造成View的重绘,代码里可以看见通过RenderNode.offsetTopAndBottom来实现的。(Draw绘制完的东西保存在RenderNode里面,所以位置的修改可以直接修改RenderNode)
invalidate 绘制当前的ViewTree, 这里的目的上让上面设置的RenderNode生效。

2: 事件传递
事件传递的关键是方法 canScrollVertically 的理解。
PS:
对于一些普通的布局, 例如 LinearLayout 是不能在其内部直接添加一个 ListView
原因的话很简单 LinearLayout 没有重写 canScrollVertically 方法。

最开始就碰到canScrollVertically 这个问题困扰了两天。 后来读了源码, 才了解如果有特殊需求需要重写canScrollVertically .

package com.gank.demo.views.pulltorefresh;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by GankLi on 2016/6/20.
 */

public class UILayout extends ViewGroup {

    private static final String TAG = "Gank";

    private TextView mHeaderView;
    private View mContentView;

    private boolean mIsPulling = false;
    private int mHeaderOffset = 0;
    private static final float OFFSET_Y = 20.0f;
    private float mBeginX;
    private float mBeginY;
    private int mTotal = 0;

    public UILayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        //Header
        initHeaderVIew(context);
    }

    public UILayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //Header
        initHeaderVIew(context);
    }

    void initHeaderVIew(Context context){
        mHeaderView = new TextView(context);
        mHeaderView.setText("下拉刷新");
        mHeaderView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        mHeaderView.setGravity(Gravity.CENTER);
        mHeaderView.setBackgroundColor(Color.parseColor("#4b4b4b"));
        addView(mHeaderView);
    }

    @Override
    protected void onFinishInflate() {
        int size = getChildCount();
        Log.w(TAG, "Size: " + size);
        for (int i = 0; i < size; i++) {
            View child = getChildAt(i);
            Log.w(TAG, "View: " + child);
            if (!(child instanceof TextView)) {
                mContentView = child;
            }
        }
        super.onFinishInflate();
    }

    /**
     * 设置 Head 和 Content 的大小
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        Log.w(TAG, "---------------------Begin - onMeasure----------------------");
        Log.w(TAG, "1: HSpec: " + MeasureSpec.toString(heightMeasureSpec) + " WSpec: " + MeasureSpec.toString(widthMeasureSpec) + " H: " + getMeasuredHeight() + " W: " + getMeasuredWidth());
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        Log.w(TAG, "2: HSpec: " + MeasureSpec.toString(heightMeasureSpec) + " WSpec: " + MeasureSpec.toString(widthMeasureSpec) + " H: " + getMeasuredHeight() + " W: " + getMeasuredWidth());
        widthMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth() - getPaddingRight() - getPaddingLeft(), MeasureSpec.EXACTLY);
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight() - getPaddingTop() - getPaddingBottom(), MeasureSpec.EXACTLY);
        Log.w(TAG, "HSpec: " + MeasureSpec.toString(heightMeasureSpec) + " WSpec: " + MeasureSpec.toString(widthMeasureSpec) + " Head - HSpec: " + MeasureSpec.toString(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)));
        mContentView.measure(widthMeasureSpec, heightMeasureSpec);
        mHeaderView.measure(widthMeasureSpec, MeasureSpec
                .makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        Log.w(TAG, "---------------------End - onMeasure----------------------");
    }

    /**
     * 设置 Head 和 Content 的位置
     */
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        Log.w(TAG, "=============Begin - onLayout=============");
        Log.w(TAG, "changed: " + changed + "(" + l + "," + t + ") - (" + r + "," + b + ")");
        if (mContentView == null) {
            return;
        }
        int height = getMeasuredHeight();
        int width = getMeasuredWidth();

        Log.w(TAG, "H: " + height + " W: " + width);
        Log.w(TAG, "mContentView:  (0," + mHeaderOffset + ") - (" + width + "," + (height + mHeaderOffset) + ")");
        Log.w(TAG, "mHeaderView:  (0," + (mHeaderView.getMeasuredHeight() + mHeaderOffset) + ") - (" + width + "," + mHeaderOffset + ")");

        mContentView.layout(0, mHeaderOffset, width, height + mHeaderOffset);
        mHeaderView.layout(0, mHeaderOffset - mHeaderView.getMeasuredHeight(), width, mHeaderOffset);
        Log.w(TAG, "=============End - onLayout=============");
    }

    /**
     *  根据触摸, 显示下拉操作
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN: //按下的时候,记录位置
                mBeginX = ev.getX();
                mBeginY = ev.getY();
                mTotal = 0;
                mIsPulling = false;
                Log.w(TAG, "==ACTION_DOWN== (" + mBeginX + "," + mBeginY + ")");
                super.dispatchTouchEvent(ev);
                return true;
            case MotionEvent.ACTION_MOVE: //
                float offesty = ev.getY() - mBeginY;
                if (!mIsPulling) {
                    if (offesty > OFFSET_Y) {
                        boolean canScrollUp = mContentView.canScrollVertically(-1);
                        if (canScrollUp) {//可以继续上滑
                            return super.dispatchTouchEvent(ev);
                        }else{//出发下拉逻辑
                            mIsPulling = true;
                            mHeaderOffset = (int) (offesty - OFFSET_Y);
                            mHeaderView.setVisibility(VISIBLE);
                            invalidate();
                            return true;
                        }
                    }
                } else {//处理下拉操作
                    mHeaderOffset = (int) (offesty - OFFSET_Y);
                    mTotal += 3;
                    mHeaderView.offsetTopAndBottom(3);
                    mContentView.offsetTopAndBottom(3);
                    invalidate();
                    return true;
                }
                //Log.w(TAG, "====ACTION_MOVE==== (" + mBeginX + "," + mBeginY + ")" + " Offset: " + mHeaderOffset + " Pulling: " + mIsPulling);
                return super.dispatchTouchEvent(ev);
            case MotionEvent.ACTION_UP: //点击释放的时候, 下拉返回
                mHeaderOffset = 0;
                if (mIsPulling) {
                    mHeaderView.offsetTopAndBottom(-mTotal);
                    mContentView.offsetTopAndBottom(-mTotal);
                    invalidate();
                    mIsPulling = false;
                    return true;
                }
                Log.w(TAG, "==ACTION_UP== (" + ev.getX() + "," + ev.getY() + ")");
                return super.dispatchTouchEvent(ev);
        }
        return super.dispatchTouchEvent(ev);
    }
}

使用方式

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.gank.demo.views.pulltorefresh.UILayout
        android:id="@+id/activity_pull"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/test"/>
                <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/test"/>
            </LinearLayout>
        </ScrollView>

    </com.gank.demo.views.pulltorefresh.UILayout>
</FrameLayout>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,902评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,037评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,978评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,867评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,763评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,104评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,565评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,236评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,379评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,313评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,363评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,034评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,637评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,719评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,952评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,371评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,948评论 2 341

推荐阅读更多精彩内容