美文网首页
RecyclerView的添加头部,底部,下划线,以及模拟分页加

RecyclerView的添加头部,底部,下划线,以及模拟分页加

作者: Zebraaa | 来源:发表于2018-08-22 14:45 被阅读0次

    对于RecyclerView的使用越来越多。
    首先来看效果图


    recyclerView.gif

    我们来进行代码的编写 ,recyclerView 添加了一个头部,底部。
    首先来讲它们对应的布局创建一下。
    layout_header.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="wrap_content">
        <TextView
            android:id="@+id/tv_header"
            android:text="Header"
            android:textSize="30sp"
            android:gravity="center_horizontal|center_vertical"
            android:background="@color/colorAccent"
            android:layout_width="match_parent"
            android:layout_height="200dp" />
    
    </LinearLayout>
    
    

    layout_footer:

    <?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="wrap_content">
        <TextView
            android:id="@+id/tv_loading"
            android:gravity="center"
            android:text="footer"
            android:layout_width="match_parent"
            android:layout_height="30dp" />
    
    </LinearLayout>
    

    中间的item布局:
    layout_item:

    <?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="wrap_content">
        <TextView
            android:background="@color/colorPrimary"
            android:id="@+id/tv_test"
            android:textSize="20sp"
            android:text="123"
            android:gravity="center"
            android:textColor="#000"
            android:layout_width="match_parent"
            android:layout_height="100dp" />
    
    </LinearLayout>
    
    

    再看activity的xml,很简单就是一个RecyclerView,做之前要依赖一下recyclerview的控件

    <?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"
        android:orientation="vertical"
        >
        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_second"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </android.support.v7.widget.RecyclerView>
    
    </LinearLayout>
    

    现在我们首先来编写RecyclerView 的适配器:

    package com.example.chen.loadingtest;
    
    import android.os.Bundle;
    import android.os.Handler;
    import android.support.annotation.Nullable;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.DividerItemDecoration;
    import android.support.v7.widget.GridLayoutManager;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.MotionEvent;
    import android.view.View;
    import android.widget.Toast;
    
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * author : chen
     * date   : 2018/8/22  10:16
     * desc   :
     */
    public class SecondActivity extends AppCompatActivity {
    
        private RecyclerView rv_second;
        private List<String> data = new ArrayList<>();
        private SecAdapter adapter;
        private GridLayoutManager manager;
        private int lastVisibleItem = 0;
        private final int PAGE_COUNT = 10;   //模拟分页10个数据为一页
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_second);
            initView();
            initData();
            initRecy();
    
        }
    
    
    
        private void initRecy() {
            adapter = new SecAdapter(getDatas(0,PAGE_COUNT),this,getDatas(0,PAGE_COUNT).size()>0?true:false);
            //添加头部和底部
            adapter.setmHeadView(LayoutInflater.from(this).inflate(R.layout.layout_header,null));
            adapter.setmFooterView(LayoutInflater.from(this).inflate(R.layout.layout_footer,null));
    
            manager = new GridLayoutManager(this,1);
            rv_second.setLayoutManager(manager);
            //添加下划线
            rv_second.addItemDecoration(new DividerItemDecoration(this,MyDecoration.VERTICAL_LIST));
            rv_second.setAdapter(adapter);
            //item的监听事件
            adapter.setOnItemListener(new SecAdapter.OnItemListener() {
                @Override
                public void OnItemClick(View view) {
                    int position = rv_second.getChildAdapterPosition(view);
                    Toast.makeText(SecondActivity.this,data.get(position-1),Toast.LENGTH_SHORT).show();
                }
            });
            rv_second.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    //对于滑动的事件操作
                    if(newState==RecyclerView.SCROLL_STATE_IDLE){
                        Log.e("tag","多少个:"+adapter.getItemCount());
                        Log.e("tag","现在个:"+lastVisibleItem);
                        Log.e("tag","fadeTip:"+adapter.isfadeTip());
                        //lastVisibleItem最后可看见的item
                        if(adapter.isfadeTip()==false&&lastVisibleItem+1==adapter.getItemCount()){
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    //减去2是因为头部和底部是增加出来的View
                                    updateData(adapter.getItemCount()-2,adapter.getItemCount()+PAGE_COUNT-2);
                                }
                            },1000);
    
                        }else if(adapter.isfadeTip()==true){
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    updateData(adapter.getItemCount()-2,adapter.getItemCount()+PAGE_COUNT-2);
                                }
                            },1000);
    
                        }
    
                    }
                }
    
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    //找到对吼一个可见的item
                    lastVisibleItem = manager.findLastVisibleItemPosition();
    
                }
            });
        }
    
        private void updateData(int fromIndex, int toIndex) {
            List<String> newDatas = getDatas(fromIndex, toIndex);
            Log.e("tag","数量:"+newDatas.size());
            if (newDatas.size() > 0) {
                adapter.updateList(newDatas, true);
            } else {
                adapter.updateList(null, false);
            }
    
        }
    
        private List<String> getDatas(final int firstIndex, final int lastIndex) {
            List<String> resList = new ArrayList<>();
            for (int i = firstIndex; i < lastIndex; i++) {
                if (i < data.size()) {
                    resList.add(data.get(i));
                }
            }
            return resList;
        }
    
        private void initData() {
            for(int i=1;i<=41;i++){
                data.add("序号"+i);
            }
        }
    
        private void initView() {
            rv_second = (RecyclerView) findViewById(R.id.rv_second);
        }
    }
    
    
    

    下划线:

    package com.example.chen.loadingtest;
    
    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;
    
    /**
     * author : chen
     * date   : 2018/8/22  11:03
     * desc   :
     */
    public class MyDecoration extends RecyclerView.ItemDecoration{
    
        private Context mContext;
        private Drawable mDivider;
        private int mOrientation;
        public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
        public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;
    
        //我们通过获取系统属性中的listDivider来添加,在系统中的AppTheme中设置
        public static final int[] ATRRS  = new int[]{
                android.R.attr.listDivider
        };
    
        public MyDecoration(Context context, int orientation) {
            this.mContext = context;
            final TypedArray ta = context.obtainStyledAttributes(ATRRS);
            this.mDivider = ta.getDrawable(0);
            ta.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, RecyclerView.State state) {
            if (mOrientation == HORIZONTAL_LIST){
                drawVerticalLine(c, parent, state);
            }else {
                drawHorizontalLine(c, parent, state);
            }
        }
    
        //画横线, 这里的parent其实是显示在屏幕显示的这部分
        public void drawHorizontalLine(Canvas c, RecyclerView parent, RecyclerView.State state){
            int left = parent.getPaddingLeft();
            int right = parent.getWidth() - parent.getPaddingRight();
            final int childCount = parent.getChildCount();
            for (int i = 0; i < childCount; i++){
                final View child = parent.getChildAt(i);
    
                //获得child的布局信息
                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);
                //Log.d("wnw", left + " " + top + " "+right+"   "+bottom+" "+i);
            }
        }
    
        //画竖线
        public void drawVerticalLine(Canvas c, RecyclerView parent, RecyclerView.State state){
            int top = parent.getPaddingTop();
            int bottom = parent.getHeight() - parent.getPaddingBottom();
            final int childCount = parent.getChildCount();
            for (int i = 0; i < childCount; i++){
                final View child = parent.getChildAt(i);
    
                //获得child的布局信息
                final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams)child.getLayoutParams();
                final int left = child.getRight() + params.rightMargin;
                final int right = left + mDivider.getIntrinsicWidth();
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(c);
            }
        }
    
        //由于Divider也有长宽高,每一个Item需要向下或者向右偏移
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            if(mOrientation == HORIZONTAL_LIST){
                //画横线,就是往下偏移一个分割线的高度
                outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
            }else {
                //画竖线,就是往右偏移一个分割线的宽度
                outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
            }
        }
    }
    
    
    

    也是可以结合android.support.v4.widget.SwipeRefreshLayout控件来进行使用的:

    相关文章

      网友评论

          本文标题:RecyclerView的添加头部,底部,下划线,以及模拟分页加

          本文链接:https://www.haomeiwen.com/subject/lyfyiftx.html