基于SwipeRefreshLayout的上拉加载控件

2022-09-12 20:06:34 浏览数 (2)

大家好,又见面了,我是你们的朋友全栈君。

距离上一篇博客,居然已经过了大半年的时间,时间过得真快啊!CSDN最近大改版,各种用户体验也是被无数人吐槽,让人提不起任何写博客的兴趣,不过,该写的博客还是必须得写,话不多话,直接进入正题。 现在项目中用列表来展示数据比比皆是,ListView和RecyclerView大家也是耳熟能详。实际项目中,后台肯定的接口肯定都是分页的,那么,分页加载也是自然而然的事,下面基于Google原生的下拉刷新控件SwipeRefreshLayout,实现上拉加载更多的功能。直接上代码: CustomSwipeRefreshLayout.java

代码语言:javascript复制
package com.jackie.sample.custom_view;

import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;

import com.jackie.sample.R;
import com.jackie.sample.utils.LogUtils;

/** * Created by Jackie on 2018/1/11 * 自定义下拉刷新上拉加载控件 目前只支持ListView */
public class CustomSwipeRefreshLayout extends SwipeRefreshLayout implements OnScrollListener { 
   
    private Context mContext;

    // 滑动到最下面时的上拉操作
    private int mTouchSlop;

    // ListView
    private ListView mListView;

    // 上拉监听器, 到了最底部的上拉加载操作
    private OnLoadListener mOnLoadListener;
    private OnScrollListener mOnScrollListener;
    private OnScrollStateChangeListener mOnScrollStateChangeListener;

    // ListView的加载中FooterView
    private View mFooterView;

    // 按下时的y坐标
    private int mDownY;
    // 移动时的y坐标, 与mDownY一起用于滑动到底部时判断是上拉还是下拉
    private int mMoveY;
    // 是否在加载中 (上拉加载更多)
    private boolean mIsLoading = false;

    private int mCanLoadCount = 6;
    private int mStartLoadCount = 3;

    public CustomSwipeRefreshLayout(Context context) {
        this(context, null);
    }

    public CustomSwipeRefreshLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

        initView(context);
    }

    private void initView(Context context) {
        mContext = context;

        // 表示滑动的时候,手的移动要大于这个距离才开始移动控件。如果小于这个距离就不触发移动控件,如ViewPager就是用这个距离来判断用户是否翻页
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();

        // 设置下拉progress的开始位置和结束位置
// setProgressViewOffset(false, DensityUtils.dp2px(context, 20), DensityUtils.dp2px(context, 80));
    }

    @Override  
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {  
        super.onLayout(changed, left, top, right, bottom);

        // 初始化ListView对象 
        if (mListView == null) {
            getListView();
        }
    }  

    /** * 获取ListView对象 */  
    private void getListView() {  
        int childCount = getChildCount();

        if (childCount > 0) {
            for (int i = 0; i < childCount; i  ) {
                View childView = getChildAt(i);

                if (childView instanceof ListView) {
                    mListView = (ListView) childView;

                    // 设置滚动监听器给ListView, 使得滚动的情况下也可以自动加载
                    mListView.setOnScrollListener(this);
                }
            }
        }  
    }

    /** * @param event * @return */
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {  
        final int action = event.getAction();  

        switch (action) {  
            case MotionEvent.ACTION_DOWN:
                // 按下
                mDownY = (int) event.getRawY();

                break;
            case MotionEvent.ACTION_MOVE:
                // 移动
                mMoveY = (int) event.getRawY();

                break;
            case MotionEvent.ACTION_UP:  
                // 抬起
                if (canLoad()) {  
                    loadData();  
                }

                break;  
            default:  
                break;  
        }  

        return super.dispatchTouchEvent(event);  
    }  

    // 是否可以加载更多, 条件是到了最底部, ListView不在加载中, 且为上拉操作.
    private boolean canLoad() {
        if (mListView == null) {
            LogUtils.showLog("不能加载");
            return false;
        }

        return isBottom() && !mIsLoading && isPullUp() && mListView.getAdapter().getCount() > mCanLoadCount && !isRefreshing();
    }

    /** * 设置列表的数目达到多少条才能上拉加载更多 * @param canLoadCount */
    public void setCanLoadCount(int canLoadCount) {
        this.mCanLoadCount = canLoadCount;
    }

    // 判断是否到了最底部
    private boolean isBottom() {
        if (mListView != null && mListView.getAdapter() != null) {  
            return mListView.getLastVisiblePosition() >= (mListView.getAdapter().getCount() - mStartLoadCount);
        }

        return false;  
    }

    /** * 设置上拉到列表倒数第几条的时候开始加载更多 * @param startLoadCount */
    public void setStartLoadCount(int startLoadCount) {
        this.mStartLoadCount = startLoadCount;
    }

    // 是否是上拉操作
    private boolean isPullUp() {  
        return (mDownY - mMoveY) >= mTouchSlop;
    }  

    // 如果到了最底部,而且是上拉操作.那么执行onLoad方法
    private void loadData() {  
        if (mOnLoadListener != null) {  
            // 设置状态 
            setLoading(true);

            mOnLoadListener.onLoad();
        }  
    }  

    private void setLoading(boolean loading) {
        mIsLoading = loading;

        if (mIsLoading) {
            mFooterView = LayoutInflater.from(mContext).inflate(R.layout.listview_footer, null, false);

// if (mListView.getFooterViewsCount() <= 0) { 
   
// mListView.addFooterView(mFooterView);
// }
//
// mFooterView.setVisibility(View.VISIBLE);

            mListView.addFooterView(mFooterView);
        } else {
            if (mListView == null || mListView.getFooterViewsCount() <= 0 || mListView.getAdapter() == null || mFooterView == null) {
                return;
            }

// mFooterView.setVisibility(View.GONE);

            mListView.removeFooterView(mFooterView);

// ObjectAnimator animation = ObjectAnimator.ofFloat(mFooterView, "scaleY", 1, 0);
// animation.setDuration(100);
// animation.start();
// animation.addListener(new Animator.AnimatorListener() { 
   
// public void onAnimationStart(Animator arg0) { 
   
//
// }
//
// public void onAnimationRepeat(Animator arg0) { 
   
//
// }
//
// public void onAnimationEnd(Animator arg0) { 
   
// mListView.removeFooterView(mFooterView);
//
// }
//
// public void onAnimationCancel(Animator arg0) { 
   
//
// }
// });

            mDownY = 0;
            mMoveY = 0;
        }  
    }  

    // 设置上拉加载的监听
    public void setOnLoadListener(OnLoadListener loadListener) {  
        mOnLoadListener = loadListener;  
    }

    // 滑动状态改变的代理
    @Override  
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (mOnScrollStateChangeListener != null) {
            mOnScrollStateChangeListener.onScrollStateChanged(view, scrollState);
        }
    }  

    @Override  
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (mOnScrollListener != null) {
            mOnScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
        }

        // 滚动时到了最底部也可以加载更多 
        if (canLoad()) {  
            loadData();  
        }
    }  

    // 加载更多的监听器
    public interface OnLoadListener { 
   
        void onLoad();
    }

    public interface OnScrollListener { 
   
        void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount);
    }

    public interface OnScrollStateChangeListener { 
   
        void onScrollStateChanged(AbsListView listView, int state);
    }

    public void onRefreshComplete() {
        setLoading(false);
        setRefreshing(false);

// if (isPullUp()) { 
   
// setLoading(false);
// } else { 
   
// setRefreshing(false);
// }
    }

    public void setOnScrollListener(OnScrollListener onScrollListener) {
        this.mOnScrollListener = onScrollListener;
    }

    public void setOnScrollStateChangeListener(OnScrollStateChangeListener onScrollStateChangeListener) {
        this.mOnScrollStateChangeListener = onScrollStateChangeListener;
    }
}

listview_footer.xml

代码语言:javascript复制
<?xml version="1.0" encoding="utf-8"?>  
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:paddingBottom="8dp" android:paddingTop="5dp" >

    <ProgressBar android:layout_width="wrap_content" android:layout_height="wrap_content" style="?android:attr/progressBarStyleSmall" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:paddingRight="100dp" android:indeterminate="true" />  

    <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:paddingTop="5dip" android:text="加载更多..." android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="@android:color/darker_gray" android:textSize="14sp" android:textStyle="bold" />  

</RelativeLayout>  

可以看出代码很简单,注释很清楚,这里就不作赘述。由于SwipeRefreshLayout本身就是下拉加载控件,这样封装后,该控件就具备了下拉刷新上拉加载更多的功能,用法没有任务变化:

代码语言:javascript复制
<com.jackie.sample.custom_view.CustomSwipeRefreshLayout
        android:id="@ id/swipe_refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <ListView
        android:id="@ id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="none" />
</com.jackie.sample.custom_view.CustomSwipeRefreshLayout>

唯一的不足之处,该控件只支持ListView,不支持RecyclerView,有兴趣的同学可以自行优化。 SwipeRefreshLayoutActivity .java

代码语言:javascript复制
package com.jackie.sample.material_design;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.jackie.sample.R;
import com.jackie.sample.custom_view.CustomSwipeRefreshLayout;
import com.jackie.sample.utils.ThreadUtils;

import java.util.ArrayList;
import java.util.List;

/** * Created by Jackie on 2018/1/11. * 自定下拉刷新上拉加载控件 */

public class SwipeRefreshLayoutActivity extends AppCompatActivity { 
   
    private CustomSwipeRefreshLayout mSwipeRefreshLayout;
    private ListView mListView;

    private ArrayAdapter mAdapter;

    private List<String> mList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_swipe_refresh_layout);

        initView();
        initData();
        initEvent();
    }

    private void initView() {
        mSwipeRefreshLayout = (CustomSwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
        mListView = (ListView) findViewById(R.id.list_view);

        mList = new ArrayList<>();
    }

    private void initData() {
        for (int i = 0; i < 20; i  ) {
            mList.add("第"   (i   1)   "条数据");
        }

        mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mList);
        mListView.setAdapter(mAdapter);
    }

    private void refreshData() {
        ThreadUtils.newThread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < 5; i  ) {
                            mList.add("第"   (i   1)   "条数据");
                        }

                        mAdapter.notifyDataSetChanged();

                        mSwipeRefreshLayout.onRefreshComplete();
                    }
                });
            }
        });
    }

    private void initEvent() {
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);

        /** * 下拉刷新 */
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
               refreshData();
            }
        });

        /** * 上拉加载更多 */
        mSwipeRefreshLayout.setOnLoadListener(new CustomSwipeRefreshLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                refreshData();
            }
        });
    }
}

效果图如下:

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/152910.html原文链接:https://javaforall.cn

0 人点赞