Android SwipeRefreshLayout+RecyclerView下拉刷新与上拉加载

1、SwipeRefrshLayout是Google官方更新的一个Widget,可以实现下拉刷新的效果。该控件集成自ViewGroup在support-v4兼容包下,不过我们需要升级supportlibrary的版本到19.1以上。
基本使用的方法如下:

setOnRefreshListener(OnRefreshListener):添加下拉刷新监听器
setRefreshing(boolean):显示或者隐藏刷新进度条
isRefreshing():检查是否处于刷新状态
setColorSchemeResources():设置进度条的颜色主题,最多设置四种,以前的setColorScheme()方法已经弃用了。

2、 RecyclerView实现的列表,默认情况下面是不带下拉刷新和上拉加载更多效果的,但是我在我们的实际项目当中,为了提高用户体验,这种效果一般都需要实现。使用footer底部样式的xml来自定义加载更多的时候UI显示效果。

3、引入RecyclerView支持类库

4、使用SwipeRefreshLayout和RecyclerView布局activity_recycler_refresh.xml






    
    



RecyclerView的item简单布局item_recycler.xml







底部加载更多时显示的布局栏footer.xml







5、引入SwipeRefreshLayout和RecyclerView的RecyclerRefreshActivity

public class RecyclerRefreshActivity extends Activity {
    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private RefreshRecyclerAdapter adapter;
    private LinearLayoutManager linearLayoutManager;
    private int lastVisibleItem;
    private List lists;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_recycler_refresh);

    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefreshlayout);
    recyclerView = (RecyclerView) findViewById(R.id.recyclerview);

    // 设置刷新时动画的颜色,可以设置4个
    swipeRefreshLayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
    swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light,
            android.R.color.holo_orange_light, android.R.color.holo_green_light);
    swipeRefreshLayout.setProgressViewOffset(false, 0,
            (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics()));

    linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setOrientation(OrientationHelper.VERTICAL);
    recyclerView.setLayoutManager(linearLayoutManager);

    initData();

    adapter = new RefreshRecyclerAdapter(this, lists);
    recyclerView.setAdapter(adapter);

    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            //模拟网络请求
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    List newDatas = new ArrayList();
                    for (int i = 0; i < 5; i++) {
                        int index = i + 1;
                        newDatas.add("new item" + index);
                    }
                    adapter.addItem(newDatas);
                    swipeRefreshLayout.setRefreshing(false);
                    Toast.makeText(RecyclerRefreshActivity.this, "更新了" + newDatas.size() + "条数据",
                            Toast.LENGTH_SHORT).show();
                }
            }, 5000);

        }

    });
    // RecyclerView滑动监听
    recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == adapter.getItemCount()) {
                adapter.changeMoreStatus(RefreshRecyclerAdapter.LOADING_MORE);
                //模拟网络请求
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        List newDatas = new ArrayList();
                        for (int i = 0; i < 5; i++) {
                            int index = i + 1;
                            newDatas.add("add more item" + index);
                        }
                        adapter.addMoreItem(newDatas);
                        adapter.changeMoreStatus(RefreshRecyclerAdapter.PULLUP_LOAD_MORE);
                    }
                }, 2500);
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
        }
    });
}

// 初始化模拟数据
private void initData() {
    lists = new ArrayList();
    for (int i = 0; i < 20; i++) {
        int index = i + 1;
        lists.add("item初始化数据" + index);
        }

    }
}

绑定RecyclerView的适配器,用于加载数据RefreshRecyclerAdapter

public class RefreshRecyclerAdapter extends RecyclerView.Adapter {
/**
 * 上拉加载更多
 */
public static final int PULLUP_LOAD_MORE = 0;
/**
 *  正在加载中
 */
public static final int LOADING_MORE = 1;
/**
 *  上拉加载更多状态-默认为0
 */
private int loading_status = 0;

/**
 *  普通Item View
 */
private static final int TYPE_ITEM = 0;
/**
 *  底部FootView
 */
private static final int TYPE_FOOTER = 1; 

private LayoutInflater mInflater;
private List lists;

public RefreshRecyclerAdapter(Context context, List lists) {
    this.mInflater = LayoutInflater.from(context);
    this.lists = lists;
}

/**
 * item显示类型
 * 
 * @param parent
 * @param viewType
 * @return
 */
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    // 进行判断显示类型,来创建返回不同的View
    if (viewType == TYPE_ITEM) {
        View view = mInflater.inflate(R.layout.item_recycler, parent, false);
        // 这边可以做一些属性设置,甚至事件监听绑定
        // view.setBackgroundColor(Color.RED);
        ItemViewHolder itemViewHolder = new ItemViewHolder(view);
        return itemViewHolder;
    } else if (viewType == TYPE_FOOTER) {
        View foot_view = mInflater.inflate(R.layout.footer, parent, false);
        // 这边可以做一些属性设置,甚至事件监听绑定
        // view.setBackgroundColor(Color.RED);
        FootViewHolder footViewHolder = new FootViewHolder(foot_view);
        return footViewHolder;
    }
    return null;
}

/**
 * 数据的绑定显示
 * 
 * @param holder
 * @param position
 */
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    if (holder instanceof ItemViewHolder) {
        ((ItemViewHolder) holder).tvItem.setText(lists.get(position));
        holder.itemView.setTag(position);
    } else if (holder instanceof FootViewHolder) {
        FootViewHolder footViewHolder = (FootViewHolder) holder;
        switch (loading_status) {
        case PULLUP_LOAD_MORE:
            footViewHolder.tvFooter.setText("上拉加载更多...");
            break;
        case LOADING_MORE:
            footViewHolder.tvFooter.setText("正在加载更多数据...");
            break;
        }
    }
}

/**
 * 进行判断是普通Item视图还是FootView视图
 */
@Override
public int getItemViewType(int position) {
    // 最后一个item设置为footerView
    if (position + 1 == getItemCount()) {
        return TYPE_FOOTER;
    } else {
        return TYPE_ITEM;
    }
}

@Override
public int getItemCount() {
    return lists.size() + 1;
}

// 自定义的ViewHolder,持有每个Item的的所有界面元素
public static class ItemViewHolder extends RecyclerView.ViewHolder {
    public TextView tvItem;

    public ItemViewHolder(View view) {
        super(view);
        tvItem = (TextView) view.findViewById(R.id.tv_item);
    }
}

/**
 * 底部FootView布局
 */
public static class FootViewHolder extends RecyclerView.ViewHolder {
    private TextView tvFooter;

    public FootViewHolder(View view) {
        super(view);
        tvFooter = (TextView) view.findViewById(R.id.tv_foot_item);
    }
}

// 添加数据,下拉
public void addItem(List newDatas) {
    newDatas.addAll(lists);
    lists.removeAll(lists);
    lists.addAll(newDatas);
    notifyDataSetChanged();
}
// 添加数据,上拉
public void addMoreItem(List newDatas) {
    lists.addAll(newDatas);
    notifyDataSetChanged();
}

/**
 * 改变状态
 */
public void changeMoreStatus(int status) {
    loading_status = status;
    notifyDataSetChanged();
    }
}

完成下拉刷新和上拉加载更多

你可能感兴趣的:(Android常用)