Android5.0 RecyclerView的使用

2016-11-26  本文已影响91人  markzl

刚刚开始写博客,拿一些简单出来练练手,Demo地址就不贴出来了,RecyclerView的适配器我一直都是使用CaMnter的EasyAdapter,这里贴出的地址可以参考下:https://github.com/CaMnter/EasyRecyclerView ,感觉鸿洋大神的BaseAdapter有点绕,就使用这个了。下面Adapter是随手写的...

然而

注意的地方:

布局(layout)

\res\layout\activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.aqtc.recyclerviewdemo.MainActivity">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </android.support.v4.widget.SwipeRefreshLayout>

</RelativeLayout>
\res\layout\item_view.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="70dp">

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Hello, RecylerView!"
        android:textSize="20sp"
        android:gravity="center"
        android:textColor="@color/colorPrimary"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

代码(java)

Mainactivity
private void initView() {
    mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
    // mLinearLayoutManger= (LinearLayoutManager) mRecyclerView.getLayoutManager();
    mLinearLayoutManger = new LinearLayoutManager(this);
}

private void initData() {
    MainAdapter adapter = new MainAdapter(this);
     adapter.setOnItemClickListener(new MainAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(View convertView, int position) {
            Toast.makeText(MainActivity.this,"Hello,RecyclerView!"+position,Toast.LENGTH_SHORT).show();
        }
    });
    mRecyclerView.setLayoutManager(mLinearLayoutManger);
    mRecyclerView.setAdapter(adapter);
}

private void initEvent() {
    mRecyclerView.addOnScrollListener(this.getRecyclerViewOnScrollListener());
    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            refreshData();
        }
    });
}

private void setRefreshStaus(boolean refreshStaus) {
    mRefreshStaus = refreshStaus;
}

private void refreshData() {

    if (mRefreshStaus) return;
    Log.i("xys", "下拉加载更多");
    this.setRefreshStaus(true);
    mSwipeRefreshLayout.postDelayed(new Runnable() {
        @Override
        public void run() {
            Log.i("xys", "下拉已经加载更多数据了");
            mSwipeRefreshLayout.setRefreshing(false);
            setRefreshStaus(false);
        }
    }, 2000);

}

private void getMoreData() {
    if (mRefreshStaus) return;
    Log.i("xys", "上拉加载更多");
    this.setRefreshStaus(true);
    mSwipeRefreshLayout.post(new Runnable() {
        @Override
        public void run() {
            mSwipeRefreshLayout.setRefreshing(true);
        }
    });

    mSwipeRefreshLayout.postDelayed(new Runnable() {
        @Override
        public void run() {

            Log.i("xys", "上拉已经加载更多数据了");
            mSwipeRefreshLayout.setRefreshing(false);
            setRefreshStaus(false);
        }
    }, 2000);

}

public RecyclerView.OnScrollListener getRecyclerViewOnScrollListener() {
    return new RecyclerView.OnScrollListener() {
        private boolean toLast = false;
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            /**
             * firstVisiableItem:当前可见item  lastVisiableItem: 上一个可见item
             * dy: 表示y轴滑动方向 dy = firstVisiableItem-lastVisiableItem>0 上拉
             * dx: 表示x轴滑动方向
             */
            if (dy > 0) {
                //正在向下滑动/上拉
                this.toLast = true;
            } else {
                //停止滑动或者向上滑动/下拉
                this.toLast = false;
            }
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {

            RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
            if (layoutManager instanceof LinearLayoutManager) {
                LinearLayoutManager manager = (LinearLayoutManager) layoutManager;
                //不滚动
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //最后完成显示的item的position正好是最后一掉数据的Index
                    if (toLast && manager.findLastCompletelyVisibleItemPosition() == (manager.getItemCount() - 1)) {
                        //上拉加载更多
                        getMoreData();
                    }
                }
            } else if (layoutManager instanceof StaggeredGridLayoutManager) {
                StaggeredGridLayoutManager manager = (StaggeredGridLayoutManager) recyclerView.getLayoutManager();
                //不滚动
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    /**
                     * 由于是StaggeredGridLayoutManager取最底部数据
                     * 可能有两个item,所以判断这之中有一个正好是最后一条数据的
                     * index就OK
                     */
                    int[] bottom = manager.findLastCompletelyVisibleItemPositions(new int[2]);
                    int lastItemCount = manager.getItemCount() - 1;
                    if (toLast && (bottom[0] == lastItemCount || bottom[1] == lastItemCount)) {
                        //上拉加载更多
                        Log.i("xys", "上拉加载更多");
                    }
                }
            }

        }
    };
}
MainAdapter
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {

    private Context mContext;
    private MainAdapter.OnItemClickListener onItemClickListener = null;
    private MainAdapter.OnItemLongClickListener onItemLongClickListener = null;

    public MainAdapter(Context context) {

        mContext=context;
    }

    @Override
    public MainAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView=LayoutInflater.from(mContext).inflate(R.layout.item_view,parent,false);
        ViewHolder holder=new ViewHolder(itemView);
        return holder;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {

        holder.itemView.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                onItemClickListener.onItemClick(holder.itemView,position);
            }
        });
        holder.setData(position);
    }

    @Override
    public int getItemCount() {
        return 50;
    }

    class ViewHolder extends RecyclerView.ViewHolder{

        private TextView tv_name;
        public ViewHolder(View itemView) {
            super(itemView);
            tv_name= (TextView) itemView.findViewById(R.id.tv_name);
        }
        public void setData(int position){
            tv_name.setText("Hello, RecyclerView!"+position);
        }
    }
 
    public void setOnItemClickListener(MainAdapter.OnItemClickListener onItemClickListener) {

        this.onItemClickListener = onItemClickListener;
    }

    public void setOnItemLongClickListener(MainAdapter.OnItemLongClickListener onItemLongClickListener) {

        this.onItemLongClickListener = onItemLongClickListener;
    }

    public interface OnItemClickListener {
        void onItemClick(View convertView, int position);
    }

    public interface OnItemLongClickListener {
        boolean onItemLongClick(View convertView, int position);
    }

}
EasyBorderDividerItemDecoration(分隔线)
public class EasyBorderDividerItemDecoration extends RecyclerView.ItemDecoration {

    private final int verticalItemSpacingInPx;
    private final int horizontalItemSpacingInPx;

    public EasyBorderDividerItemDecoration(int verticalItemSpacingInPx, int horizontalItemSpacingInPx) {
        this.verticalItemSpacingInPx = verticalItemSpacingInPx;
        this.horizontalItemSpacingInPx = horizontalItemSpacingInPx;
    }

    /**
     * set border
     *
     * @param outRect outRect
     * @param view view
     * @param parent parent
     * @param state state
     */
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) view.getLayoutParams();
        int itemPosition = layoutParams.getViewLayoutPosition();
        int childCount = parent.getAdapter().getItemCount();

        int left = this.horizontalItemSpacingInPx;
        int right = this.horizontalItemSpacingInPx;

        int top = getItemTopSpacing(itemPosition);
        int bottom = getItemBottomSpacing(itemPosition, childCount);
        outRect.set(left, top, right, bottom);
    }

    /**
     * get the item bottom spacing
     *
     * @param itemPosition itemPosition
     * @param childCount childCount
     * @return int
     */
    private int getItemBottomSpacing(int itemPosition, int childCount) {
        if (isLastItem(itemPosition, childCount)) {
            return this.verticalItemSpacingInPx;
        }
        return this.verticalItemSpacingInPx / 2;
    }

    /**
     * get the item top spacing
     *
     * @param itemPosition itemPosition
     * @return int
     */
    private int getItemTopSpacing(int itemPosition) {
        if (isFirstItem(itemPosition)) {
            return this.verticalItemSpacingInPx;
        }
        return this.verticalItemSpacingInPx / 2;
    }

    /**
     * is the first item
     *
     * @param itemPosition itemPosition
     * @return boolean
     */
    private boolean isFirstItem(int itemPosition) {
        return itemPosition == 0;
    }

    /**
     * is the last item
     *
     * @param itemPosition itemPosition
     * @param childCount childCount
     * @return boolean
     */
    private boolean isLastItem(int itemPosition, int childCount) {
        return itemPosition == childCount - 1;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读