RecyclerView 项目实例

项目中使用到recyclerView来取代了Listview,这里主要用来记录recyclerview的使用方法步骤。

routeRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        routeRecyclerview.setItemAnimator(new FadeInAnimator());
        routeRecyclerview.addItemDecoration(new RecyclerItemDivider(this));
        routeAdapter = new RouteAdapter(this, datas, onItemClickListener);
        AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(routeAdapter);
        ScaleInAnimationAdapter scaleAdapter = new ScaleInAnimationAdapter(alphaAdapter);
        routeRecyclerview.setAdapter(scaleAdapter);
        routeRecyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                // 是否满足加载更多
                if (routeAdapter.isShowLoadMore()) {
                    LinearLayoutManager layoutManager = (LinearLayoutManager) routeRecyclerview.getLayoutManager();
                    int totalItemCount = layoutManager.getItemCount();//获取总大小
                    int visibleItem = layoutManager.getChildCount();//获取屏幕中可见条总数
                    if (visibleItem > 0 && layoutManager.findLastVisibleItemPosition() >= totalItemCount - 1) {
                        if (!isLoading) {//加载更多逻辑
                            isLoading = true;
                            if (Config.isNetworkConnected(mContext)) {
                                if (pageNoResult != null && pageNoResult.getHasMore()) {
                                    currentPage++;
                                    mPageBuilder.setPageNo(currentPage);
                                    loadData();
                                }
                            } else {
                                isLoading = false;
                            }
                        }
                    }
                }
            }
        });

1.添加recycleview的layoutmanager,主要用三种形式:LinearLayoutManager(线性)、 GridLayoutManager(网格) 、 StaggeredGridLayoutManager(瀑布流)

2.添加item动画 recyclerview.setItemAnimator(new DefaultItemAnimator()); //即使不设置,默认也是这个动画

3.添加条目间的分割线

public class RecyclerItemDivider extends RecyclerView.ItemDecoration {

    private Drawable mDivider;

    public RecyclerItemDivider(Context context) {
        mDivider = context.getResources().getDrawable(R.drawable.favour_item_driver);
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent) {
        drawVertical(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);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
        outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
    }
}

4.创建recycleView填充器

public class RouteAdapter extends RecyclerView.Adapter {

    /**
     * 全局上下文
     */
    public Context mContext;
    /**
     * 是否显示加载更多
     */
    public boolean isShowLoadMore = false;
    /**
     * 加载更多布局id
     */
    public int loadMoreLayout = R.layout.recycler_view_load_more;
    /**
     * 正常显示数据的item布局
     */
    public int itemLayout = R.layout.activity_route_item;
    /**
     * 数据源
     */
    public List datas = null;

    public OnItemClickListener onItemClickListener = null;


    public RouteAdapter(Context context, List datas, OnItemClickListener onItemClickListener) {
        this.mContext = context;
        this.datas = datas;
        this.onItemClickListener = onItemClickListener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(mContext).inflate(viewType, parent, false);
        return new ViewHolder(mContext, v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        if (getItemViewType(position) != itemLayout) {
            // 设置加载更多布局是否显示
            if (getItemViewType(position) == loadMoreLayout) {
                if (Config.isNetworkConnected(mContext)) {
                    holder.itemView.setVisibility(View.VISIBLE);
                } else {
                    holder.itemView.setVisibility(View.GONE);
                    Config.showFiledToast((Activity) mContext);
                }
            }
            return;
        }

        // 设置显示内容
        holder.routeItemTitle.setText(datas.get(position).getStatusDesc());
        holder.routeItemTime.setText(tipformatter.format(datas.get(position).getCreateTime() * 1000L));
        holder.routeItemBook.setText(datas.get(position).getCar());
        holder.routeItemCar.setText(datas.get(position).getLicensePlateNumber());
        holder.routeItemAddress.setText(datas.get(position).getGetCarAddress());
        // 设置显示颜色
        showStatus(holder, datas.get(position).getStatus());

        holder.routeItemRootRela.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
            @Override
            public void onComplete(RippleView rippleView) {
                if (datas != null && datas.size() > position) {
                    onItemClickListener.onItemClick(datas.get(position));
                }
            }
        });

        holder.itemView.setTag(datas.get(position));
    }

    @Override
    public int getItemCount() {
        if (datas != null && datas.size() > 0) {
            if (isShowLoadMore)
                return datas.size() + 1;
            else
                return datas.size();
        }
        return 0;
    }

    @Override
    public int getItemViewType(int position) {
        int viewType = itemLayout;
        if (position == getItemCount() - 1 && isShowLoadMore) {
            viewType = loadMoreLayout;
        }
        return viewType;
    }

    SimpleDateFormat tipformatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    class ViewHolder extends RecyclerView.ViewHolder {

        public RippleView routeItemRootRela;
        public TextView routeItemTitle;// 行程title
        public TextView routeItemTime;// 行程时间
        public TextView routeItemBook;// 预定车辆
        public TextView routeItemCar;// 车牌
        public TextView routeItemAddress;// 取车地点

        public ViewHolder(final Context mContext, final View itemView) {
            super(itemView);

            routeItemRootRela = (RippleView) itemView.findViewById(R.id.route_item_root_rela);
            routeItemTitle = (TextView) itemView.findViewById(R.id.route_item_title_text);
            routeItemTime = (TextView) itemView.findViewById(R.id.route_item_time_text);
            routeItemBook = (TextView) itemView.findViewById(R.id.route_item_book_content);
            routeItemCar = (TextView) itemView.findViewById(R.id.route_item_car_content);
            routeItemAddress = (TextView) itemView.findViewById(R.id.route_item_address_content);
        }
    }


    // ############################## get set方法 ############################################

    public void showStatus(ViewHolder holder, int status) {
        // 已取消
        if (status == OrderCommon.OrderFormStatus.renter_cancel_VALUE) {
            holder.routeItemTitle.setTextColor(mContext.getResources().getColor(R.color.c4));
        }
        // 已完成
        else if (status == OrderCommon.OrderFormStatus.order_finish_VALUE) {
            holder.routeItemTitle.setTextColor(mContext.getResources().getColor(R.color.c3));
        }
        // 待取车、在用车、待支付
        else if (status == OrderCommon.OrderFormStatus.wait_get_car_VALUE ||
                status == OrderCommon.OrderFormStatus.using_car_VALUE ||
                status == OrderCommon.OrderFormStatus.wait_pay_VALUE) {
            holder.routeItemTitle.setTextColor(mContext.getResources().getColor(R.color.c8));
        } else {
            holder.routeItemTitle.setTextColor(mContext.getResources().getColor(R.color.c8));
        }
    }

    /**
     * adapter item 点击事件
     */
    interface OnItemClickListener{

        public abstract void onItemClick(TripCommon.TripListInfo tripListInfo);
    }

    public void setmContext(Context mContext) {
        this.mContext = mContext;
    }

    public void setIsShowLoadMore(boolean isShowLoadMore) {
        this.isShowLoadMore = isShowLoadMore;
    }

    public Context getmContext() {
        return mContext;
    }

    public boolean isShowLoadMore() {
        return isShowLoadMore;
    }

}

5.自定义recycleview的条目点击事件,在adapter中实现OnItemClickListener监听接口,创建方法。并在recyclerview中实现该方法并通过adapter构造方法传入。

public OnItemClickListener onItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(TripCommon.TripListInfo tripListInfo) {
            if (tripListInfo == null) {
                showDefaultNetworkSnackBar();
                return;
            }
            //完成点击事件方法
            //。。。。。。
            //。。。。。。
        }
    };

6.为填充器设置属性动画

7.设置recycleview的滚动事件,主要用来添加上拉加载更多动作。
可以使用该该方法配合swipeRefreshLayout使用完成下拉刷新,上啦加载更多效果。

swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeResources(R.color.c1, R.color.c1, R.color.c1);//设置滚动条颜色

重写刷新方法

/**
     * 下拉刷新执行的操作
     */
    @Override
    public void onRefresh() {
        // 请求优惠券列表
        if (Config.isNetworkConnected(mContext)) {
            currentPage = 1;
            mPageBuilder.setPageNo(currentPage);
            loadData();
        } else {
            swipeRefreshLayout.setRefreshing(false);
            showDefaultNetworkSnackBar();
        }
    }

执行请求前:swipeRefreshLayout.setRefreshing(true);
执行请求后:swipeRefreshLayout.setRefreshing(false);

实现刷新样式布局

"http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.youyou.uuelectric.renter.UI.order.RouteActivity">

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

        .support.v7.widget.RecyclerView
            android:id="@+id/route_recyclerview"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clipToPadding="false"
            android:paddingTop="@dimen/s3"
            android:paddingLeft="@dimen/s3"
            android:paddingRight="@dimen/s3">.support.v7.widget.RecyclerView>
    .support.v4.widget.SwipeRefreshLayout>

你可能感兴趣的:(RecyclerView 项目实例)