安卓下拉刷新和上拉加载的具体实例

 

1.配置

//下拉刷新,上拉加载更多
api 'com.cjj.materialrefeshlayout:library:1.3.0'

2.先上项目图

 

3. DividerItemDecoration

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) {
//        Log.v("recyclerview - itemdecoration", "onDraw()");

        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);
            android.support.v7.widget.RecyclerView v = new android.support.v7.widget.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);
        }
    }
}
MainActivity
public class MainActivity extends AppCompatActivity {
    private OkHttpHelper httpHelper  =OkHttpHelper.getInstance();
    private SwipeRefreshLayout swipeRefreshLayout;
    @ViewInject(R.id.tv)
    private TextView tv;

    private RecyclerView mRecyclerView;
    private ArrayList<String> mDatas=new ArrayList<>();
    private MaterialRefreshLayout materialRefreshLayout;

    private static final int STATE_NORMAL=0;
    private static final int STATE_REFRESH=1;
    private static final int STATE_MORE=2;
    private int state = STATE_NORMAL;
    private List<PayBean.Data> mData;

    private int page=1;
    private int pagesize=20;
    private int totalpages=0;
    private PayAdapter payAdapter;
    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRecyclerView = findViewById(R.id.recycleview);
        materialRefreshLayout =findViewById(R.id.refresh);


        initRefreshLayout();
        getData();

    }


    private void initRefreshLayout(){
        materialRefreshLayout.setLoadMore(true);
        materialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
                refreshData();
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                if(page<=totalpages){
                    loadMoreData();
                }else{
                    Toast.makeText(MyApplication.getContext(),"没有更多内容了",Toast.LENGTH_SHORT).show();
                    materialRefreshLayout.finishRefreshLoadMore();
                }
            }
        });
    }

    private void loadMoreData(){
        page=++page;
        
        state=STATE_MORE;
        getData();
    }

    private void refreshData(){
        page=1;
        state=STATE_REFRESH;
        getData();
    }

    private void getData(){
        String url=Api.BASE_URL+"&page="+page+"&pagesize="+pagesize;
        httpHelper.get(url, new BaseHttpCallback() {
            @Override
            public void onRequestBefore(Request request) {

            }

            @Override
            public void onSuccess(Response response, String string) {
                PayBean payBean =JSON.parseObject(string,PayBean.class);

                page= payBean.getPageindex();
                totalpages =payBean.getTotalpages();
                mData = payBean.getData();

                showData();

            }

            @Override
            public void onError(Response response, int code, Exception e) {

            }

            @Override
            public void onFailure(Exception e) {

            }
        });
    }

    private void showData(){

        switch (state){
            case STATE_NORMAL:
                payAdapter = new PayAdapter(mData);
                mRecyclerView.setAdapter(payAdapter);
                mRecyclerView.setLayoutManager(new LinearLayoutManager(MyApplication.getContext()));
                break;
            case STATE_REFRESH:
                payAdapter.clearData();
                payAdapter.addData(0,mData);
                mRecyclerView.scrollToPosition(0);
                materialRefreshLayout.finishRefresh();
                break;
            case STATE_MORE:
                payAdapter.addData(payAdapter.getmData().size(),mData);
                mRecyclerView.scrollToPosition(payAdapter.getmData().size());
                materialRefreshLayout.finishRefreshLoadMore();
                break;
            default:
                break;
        }

    }

}
MyApplication
public class MyApplication  extends Application{
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        Fresco.initialize(this);
        context =this;
    }
    public static Context getContext(){
        return context;
    }
}
PayAdapter
public class PayAdapter extends RecyclerView.Adapter<PayAdapter.ViewHolder> {


    private List<PayBean.Data> mData;
    public OnItemClickListener mListener;
    public void setOnItemClickListener(OnItemClickListener listener){
        mListener=listener;
    }

    public PayAdapter(List<PayBean.Data> data){
        mData=data;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.view_rv_item,null,false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        PayBean.Data payBean=mData.get(position);
        holder.tv_id.setText(payBean.getId());
        holder.tv_openid.setText(payBean.getOpenid());
    }

    @Override
    public int getItemCount() {
        if(mData!=null && mData.size()>0){
            return mData.size();
        }
        return 0;
    }


    class ViewHolder extends RecyclerView.ViewHolder{

        TextView tv_id;
        TextView tv_openid;
        LinearLayout item_layout;

        public ViewHolder(View itemView) {
            super(itemView);

            tv_id =(TextView) itemView.findViewById(R.id.tv_id);
            tv_openid =(TextView) itemView.findViewById(R.id.tv_openid);



        }
    }

    public List<PayBean.Data> getmData() {
        return mData;
    }

    public interface OnItemClickListener{
        void OnClick(View view,int position,int id);
    }

    public void clearData(){
        if(mData.size()>0 && mData!=null){
            int presize= mData.size();
            mData.clear();
            notifyItemRangeRemoved(0,presize);
        }
    }



    public void addData(int position,List<PayBean.Data> datas){
        if (datas!=null && datas.size()>0){
            mData.addAll(datas);
            notifyItemRangeInserted(position,mData.size());
        }
    }

    public void removeData(){

    }

}
public class PayBean {

    public String result;
    public int pageindex;
    public int pagesize;
    public int totalrows;
    public int totalpages;
    public List<Data> data;

    public class Data {
        public String id;
        public String openid;

        public String getId() {
            return id;
        }

        public String getOpenid() {
            return openid;
        }

    }

    public int getTotalrows() {
        return totalrows;
    }

    public int getPageindex() {
        return pageindex;
    }

    public String getResult() {
        return result;
    }

    public List<Data> getData() {
        return data;
    }

    public int getTotalpages() {
        return totalpages;
    }
    public int getPagesize() {
        return pagesize;
    }


}

main_activity

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:fresco="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <com.cjj.MaterialRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:wave_height_type="normal"
        app:isLoadMore="true"
        app:overlay="true"
        app:wave_show="true"
        >
        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycleview"
            android:scrollbars="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

    </com.cjj.MaterialRefreshLayout>



    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

layout_item

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

    <LinearLayout
        android:id="@+id/item_layout"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/tv_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
        <TextView
            android:id="@+id/tv_openid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>




</LinearLayout>
public class Api {
    public static final String BASE_URL="xxxxx";

}
弄一个可以传page和pagesize的api测试即可

 

遇到的问题,adapter清空的时候,要执行

notifyItemRangeRemoved(0,presize);

 否则会报错,一个坑把。

比较全面的一个例子了

posted @ 2018-01-13 11:13  layfork  阅读(320)  评论(0编辑  收藏  举报