UI & Material DesignAndroid优秀开源第三方控件

MaterialRefreshLayout实现下拉刷新上拉加载更

2016-05-13  本文已影响4321人  菜鸟_一枚

通过本文可以了解以下几方面:

首先看下效果图:


这里写图片描述

MaterialRefreshLayout是什么

用法介绍(摘自官方文档)

AS添加依赖库,这样就不用导入整个library库,Eclipse的用户导入library库,慢慢折腾吧!(因为我觉得如果不是环境不允许你用as的话,还是放弃eclipse吧,毕竟github上很多优秀的项目都是用as的,好吧我多嘴了...)

dependencies {
    compile 'com.cjj.materialrefeshlayout:library:1.3.0'
}

在你的layout xml.添加下面的代码:

<com.cjj.MaterialRefreshLayout
    android:id="@+id/refresh"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <!--在这里我们可以添加ListView OR GridView OR RecycleView OR ScrollView OR 更多-->
      <...ListView or GridView or RecyclerView or ScrollView and more...>

</com.cjj.MaterialRefreshLayout>

在java中实现以下代码:

materialRefreshLayout = (MaterialRefreshLayout) findViewById(R.id...);
materialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
      @Override
      public void onRefresh(final MaterialRefreshLayout materialRefreshLayout) {
          //下拉刷新...
      }

       @Override
       public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
          //上拉加载更多...
       }
  }

// 结束下拉刷新...
materialRefreshLayout.finishRefresh();

// 结束上拉刷新...
 materialRefreshLayout.finishRefreshLoadMore();

下拉效果配置(官方提供了6中下拉效果,这里提供本例子中使用的,如果想要了解更多,请去官方查看)


    <com.cjj.MaterialRefreshLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/refresh"
        app:overlay="false"
        app:wave_show="true"
        app:wave_color="@color/material_green"
        app:wave_height_type="higher"
    >

好了,不多说,看代码吧。(一切还是以代码为主啊,只有代码实现了功能,才是王道)

MainActivity.java:

package com.example.materialrefreshlayoutdemo;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;

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

public class MainActivity extends AppCompatActivity {

    private MaterialRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;

    /**
     * 刚初始化的数据
     */
    private List<String> datas = new ArrayList<>();

    /**
     * 一个承接数据的数组
     */
    private List<String> mList = new ArrayList<>();
    private MyAdapter mAdapter;

    /**
     * 在上拉刷新的时候,判断,是否处于上拉刷新,如果是的话,就禁止在一次刷新,保障在数据加载完成之前
     * 避免重复和多次加载
     */
    private boolean isLoadMore = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initDatas();
    }

    /**
     * 初始化布局控件
     */
    private void initView() {

        mRefreshLayout = (MaterialRefreshLayout) findViewById(R.id.refresh);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycleview);
        initRefresh();
    }

    /**
     * 初始化加载
     */
    private void initRefresh() {
        mAdapter = new MyAdapter(datas);
        mRecyclerView.setAdapter(mAdapter);
           //下面可以自己设置默认动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
           //下面可以自己设置排版方式
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        /**
         * 设置是否上拉加载更多,默认是false,要手动改为true,要不然不会出现上拉加载
         */
        mRefreshLayout.setLoadMore(isLoadMore);
        //设置分割线
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        mRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            /**
             * 刷新的方法,我这里演示的是下拉刷新,因为没有数据,我这里也就只是toast一下
             * 如果想要实现你们自己要的结果,就会在定义一个方法,获取最新数据,或者是在次
             * 在这里调用之前获取数据的方法,以达到刷新数据的功能
             * @param materialRefreshLayout
             */
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
                //一般加载数据都是在子线程中,这里我用到了handler
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "已经没有更多数据了", Toast.LENGTH_SHORT).show();
                        /**
                         * 刷新完成后调用此方法,要不然刷新效果不消失
                         */
                        mRefreshLayout.finishRefresh();
                    }
                }, 3000);
            }

            /**
             * 上拉加载更多的方法,在这里我只是简单的模拟了加载四条数据
             * 真正用的时候,就会去定义方法,获取数据,一般都是分页,在数据端获取的时候
             * 把页数去增加一,然后在去服务端去获取数据
             * @param materialRefreshLayout
             */
            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isLoadMore = false;
                        for (int i = 0; i <= 3; i++) {
                            mList.add(i, "new City " + i);
                        }
                        //通知刷新
                        mAdapter.addLists(mAdapter.getLists().size(), mList);
                        //mRecyclerView.scrollToPosition(mAdapter.getLists().size());
                        /**
                         * 完成加载数据后,调用此方法,要不然刷新的效果不会消失
                         */
                        mRefreshLayout.finishRefreshLoadMore();
                    }
                }, 3000);
            }
        });
    }

    /**
     * 初始化数据
     */
    private void initDatas() {

        datas.add("New York");
        datas.add("Bei Jing");
        datas.add("Boston");
        datas.add("London");
        datas.add("San Francisco");
        datas.add("Chicago");
        datas.add("Shang Hai");
        datas.add("Tian Jin");
        datas.add("Zheng Zhou");
        datas.add("Hang Zhou");
        datas.add("Guang Zhou");
        datas.add("Fu Gou");
        datas.add("Zhou Kou");

    }

}

MyAdapter.java:

package com.example.materialrefreshlayoutdemo;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

/**
 * Created by 若兰 on 2016/1/26.
 * 一个懂得了编程乐趣的小白,希望自己
 * 能够在这个道路上走的很远,也希望自己学习到的
 * 知识可以帮助更多的人,分享就是学习的一种乐趣
 * QQ:1069584784
 * csdn:http://blog.csdn.net/wuyinlei
 */

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {


    /**
     * 加载布局的
     */
    private LayoutInflater mInflater;

    /**
     * 用来存放数据的集合
     */
    private List<String> mLists;

    /**
     * 自定义的item点击(在这里没有用到)
     */
    private OnItemClickListener mListener;


    /**
     * mListener get方法
     * @return
     */
    public OnItemClickListener getListener() {
        return mListener;
    }

    /**
     * mListener set方法
     * @param listener
     */
    public void setListener(OnItemClickListener listener) {
        mListener = listener;
    }

    /**
     * mLists集合的get方法  通过他可以取得数据的size();
     * @return
     */
    public List<String> getLists() {
        return mLists;
    }

    /**
     * 对以下方法的复用
     * @param lists
     */
    public void addLists(List<String> lists) {
        addLists(0, lists);
    }


    /**
     * 添加数据
     * @param position  添加的位置
     * @param lists   添加的数据
     */
    public void addLists(int position, List<String> lists) {
        //mLists = lists;
        if (lists != null && lists.size() > 0) {
            mLists.addAll(lists);
            /**
             * Notify any registered observers that the <code>itemCount</code> items starting at
             * position <code>positionStart</code> have changed.
             *
             * 通知item是从哪个地方到哪个地方已经改变了
             */
            notifyItemRangeChanged(position, mLists.size());
        }
    }


    /**
     * 构造方法,通过new对象的时候传入数据
     * @param items
     */
    public MyAdapter(List<String> items) {
        mLists = items;
    }

    // 创建ViewHolder ,相当于ListVie Adapter 的getView 方法
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        mInflater = LayoutInflater.from(parent.getContext());
        View view = mInflater.inflate(R.layout.list_item, null);
        return new MyViewHolder(view);
    }

    /**
     * 绑定数据
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.tv_text.setText(mLists.get(position));
    }

    @Override
    public int getItemCount() {
        return mLists.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        private TextView tv_text;

        public MyViewHolder(View itemView) {
            super(itemView);
            tv_text = (TextView) itemView.findViewById(R.id.tv_item);

            /**
             * 如果我们想要实现item的点击事件,就要在这处理,因为recycleview
             * 并没有给我们提供直接的点击触摸事件,这个也是他的好处(也可以理解为不好的地方)
             */
            tv_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mListener != null) {
                        mListener.onClick(v, getLayoutPosition(), mLists.get(getLayoutPosition()));
                    }
                }
            });

        }
    }

    //RecycleView的事件监听,这个要自己去写,里面的参数也是根据自己的需要去定义
    //不像listview中,已经有了item的点击监听事件
    interface OnItemClickListener {
        //自己定义
        void onClick(View v, int position, String item);
    }
}


activity_main.xml:

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

    <com.cjj.MaterialRefreshLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/refresh"
        app:overlay="false"
        app:wave_show="true"
        app:wave_color="@color/material_green"
        app:wave_height_type="higher"
    >
        <android.support.v7.widget.RecyclerView
            android:layout_width="match_parent"
            android:id="@+id/recycleview"
            android:layout_height="match_parent">

        </android.support.v7.widget.RecyclerView>

    </com.cjj.MaterialRefreshLayout>
</LinearLayout>

item_list.xml:

<?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="match_parent"
              android:orientation="vertical"
              >

    <TextView
        android:id="@+id/tv_item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:padding="10dp"
        android:text="1"
        android:gravity="center"
        android:textColor="#000"
        android:textSize="20dp"/>
</RelativeLayout>

DividerItemDecoration.java(这个网上找的):

package com.example.materialrefreshlayoutdemo;

/**
 * Created by ruolan on 2015/11/11.
 */
/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * This class is from the v7 samples of the Android SDK. It's not by me!
 * <p/>
 * See the license above for details.
 */
public class DividerItemDecoration extends RecyclerView.ItemDecoration
{

    private static final int[] ATTRS = new int[] { android.R.attr.listDivider };

    public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;

    public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;



    private Drawable mDivider;

    private int mOrientation;

    public DividerItemDecoration(Context context, int orientation)
    {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
        setOrientation(orientation);
    }

    public void setOrientation(int orientation)
    {
        if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST)
        {
            throw new IllegalArgumentException("invalid orientation");
        }
        mOrientation = orientation;
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent)
    {
        if (mOrientation == VERTICAL_LIST) {
            drawVertical(c, parent);
        } else {
            drawHorizontal(c, parent);
        }
    }

    public void drawVertical(Canvas c, RecyclerView parent)
    {
        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();

        final int childCount = parent.getChildCount();

        for (int i = 0; i < childCount; i++)
        {
            final View child = parent.getChildAt(i);
            RecyclerView v = new RecyclerView(
                    parent.getContext());
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int top = child.getBottom() + params.bottomMargin;
            final int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    public void drawHorizontal(Canvas c, RecyclerView parent)
    {
        final int top = parent.getPaddingTop();
        final int bottom = parent.getHeight() - parent.getPaddingBottom();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++)
        {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int left = child.getRight() + params.rightMargin;
            final int right = left + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, int itemPosition,
                               RecyclerView parent)
    {
        if (mOrientation == VERTICAL_LIST)
        {
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        } else
        {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        }
    }

}

好了,一个简单的上拉加载更多和下拉刷新就完成了,如果有兴趣,可以参考一下这个文章
RecycleView+SwipeRefreshLayout 实现下拉刷新地址:

MaterialRefreshLayout实现下拉刷新上拉加载更多项目的github地址:

上一篇 下一篇

猜你喜欢

热点阅读