美文网首页
Android RecyclerView应用

Android RecyclerView应用

作者: BrotherTree | 来源:发表于2018-11-21 00:41 被阅读0次

    基本使用

    配置build.gradle
    implementation 'com.android.support:recyclerview-v7:28.0.0'
    
    创建activity_recycleview.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.support.v7.widget.RecyclerView
            android:id="@+id/recycerview"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    
    </RelativeLayout>
    
    创建RecyclerViewActivity.java
    import android.content.Context;
    import android.os.Bundle;
    import android.support.annotation.NonNull;
    import android.support.annotation.Nullable;
    import android.support.v4.app.FragmentActivity;
    import android.support.v7.widget.LinearLayoutManager;
    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.ArrayList;
    import java.util.List;
    
    public class RecyclerViewActivity extends FragmentActivity {
    
        RecyclerView recyclerView;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_recycleview);
    
            recyclerView = findViewById(R.id.recycerview);
    
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            recyclerView.setAdapter(new MyAdapter(this, getListData()));
        }
    
        private List<String> getListData() {
            List<String> dataSource = new ArrayList<>();
            for (int index = 0; index < 20; index++) {
                dataSource.add(String.valueOf(index));
            }
            return dataSource;
        }
    
        class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    
            Context mContext;
            List<String> mDataSource;
    
            public MyAdapter(Context context, List<String> dataSource) {
                mContext = context;
                mDataSource = dataSource;
            }
    
            @NonNull
            @Override
            public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
                View itemView = LayoutInflater.from(mContext).inflate(R.layout.item_view, viewGroup, false);
                MyViewHolder myViewHolder = new MyViewHolder(itemView);
                return myViewHolder;
            }
    
            @Override
            public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {
                myViewHolder.valueTv.setText(mDataSource.get(i));
            }
    
            @Override
            public int getItemCount() {
                return mDataSource == null ? 0 : mDataSource.size();
            }
    
            class MyViewHolder extends RecyclerView.ViewHolder {
    
                TextView valueTv;
    
                public MyViewHolder(@NonNull View itemView) {
                    super(itemView);
    
                    valueTv = itemView.findViewById(R.id.tv_item);
                }
            }
        }
    }
    
    
    效果如下
    device-2018-11-21-000235.png
    设置分割线

    分割线的设置可以如上面示例中的一样在item的xml文件中直接设置,也可以如下方式设置

    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);
                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);
            }
        }
    }
    

    使用

    recyclerView.addItemDecoration(new DividerItemDecoration(RecyclerViewActivity.this, DividerItemDecoration.VERTICAL_LIST));
    
    效果如下
    device-2018-11-21-002353.png
    实现网格布局

    创建DividerGridItemDecoration.java

    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.GridLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.RecyclerView.LayoutManager;
    import android.support.v7.widget.RecyclerView.State;
    import android.support.v7.widget.StaggeredGridLayoutManager;
    import android.view.View;
    
    public class DividerGridItemDecoration extends RecyclerView.ItemDecoration {
    
        private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
        private Drawable mDivider;
    
        public DividerGridItemDecoration(Context context) {
            final TypedArray a = context.obtainStyledAttributes(ATTRS);
            mDivider = a.getDrawable(0);
            a.recycle();
        }
    
        @Override
        public void onDraw(Canvas c, RecyclerView parent, State state) {
    
            drawHorizontal(c, parent);
            drawVertical(c, parent);
    
        }
    
        private int getSpanCount(RecyclerView parent) {
            // 列数
            int spanCount = -1;
            LayoutManager layoutManager = parent.getLayoutManager();
            if (layoutManager instanceof GridLayoutManager) {
    
                spanCount = ((GridLayoutManager) layoutManager).getSpanCount();
            } else if (layoutManager instanceof StaggeredGridLayoutManager) {
                spanCount = ((StaggeredGridLayoutManager) layoutManager)
                        .getSpanCount();
            }
            return spanCount;
        }
    
        public void drawHorizontal(Canvas c, RecyclerView parent) {
            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.getLeft() - params.leftMargin;
                final int right = child.getRight() + params.rightMargin
                        + mDivider.getIntrinsicWidth();
                final int top = child.getBottom() + params.bottomMargin;
                final int bottom = top + mDivider.getIntrinsicHeight();
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(c);
            }
        }
    
        public void drawVertical(Canvas c, RecyclerView parent) {
            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 top = child.getTop() - params.topMargin;
                final int bottom = child.getBottom() + params.bottomMargin;
                final int left = child.getRight() + params.rightMargin;
                final int right = left + mDivider.getIntrinsicWidth();
    
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(c);
            }
        }
    
        private boolean isLastColum(RecyclerView parent, int pos, int spanCount,
                                    int childCount) {
            LayoutManager layoutManager = parent.getLayoutManager();
            if (layoutManager instanceof GridLayoutManager) {
                if ((pos + 1) % spanCount == 0)// 如果是最后一列,则不需要绘制右边
                {
                    return true;
                }
            } else if (layoutManager instanceof StaggeredGridLayoutManager) {
                int orientation = ((StaggeredGridLayoutManager) layoutManager)
                        .getOrientation();
                if (orientation == StaggeredGridLayoutManager.VERTICAL) {
                    if ((pos + 1) % spanCount == 0)// 如果是最后一列,则不需要绘制右边
                    {
                        return true;
                    }
                } else {
                    childCount = childCount - childCount % spanCount;
                    if (pos >= childCount)// 如果是最后一列,则不需要绘制右边
                        return true;
                }
            }
            return false;
        }
    
        private boolean isLastRaw(RecyclerView parent, int pos, int spanCount,
                                  int childCount) {
            LayoutManager layoutManager = parent.getLayoutManager();
            if (layoutManager instanceof GridLayoutManager) {
                childCount = childCount - childCount % spanCount;
                if (pos >= childCount)// 如果是最后一行,则不需要绘制底部
                    return true;
            } else if (layoutManager instanceof StaggeredGridLayoutManager) {
                int orientation = ((StaggeredGridLayoutManager) layoutManager)
                        .getOrientation();
                // StaggeredGridLayoutManager 且纵向滚动
                if (orientation == StaggeredGridLayoutManager.VERTICAL) {
                    childCount = childCount - childCount % spanCount;
                    // 如果是最后一行,则不需要绘制底部
                    if (pos >= childCount)
                        return true;
                } else
                // StaggeredGridLayoutManager 且横向滚动
                {
                    // 如果是最后一行,则不需要绘制底部
                    if ((pos + 1) % spanCount == 0) {
                        return true;
                    }
                }
            }
            return false;
        }
    
        @Override
        public void getItemOffsets(Rect outRect, int itemPosition,
                                   RecyclerView parent) {
            int spanCount = getSpanCount(parent);
            int childCount = parent.getAdapter().getItemCount();
            if (isLastRaw(parent, itemPosition, spanCount, childCount))// 如果是最后一行,则不需要绘制底部
            {
                outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
            } else if (isLastColum(parent, itemPosition, spanCount, childCount))// 如果是最后一列,则不需要绘制右边
            {
                outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
            } else {
                outRect.set(0, 0, mDivider.getIntrinsicWidth(),
                        mDivider.getIntrinsicHeight());
            }
        }
    }
    

    使用

    recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4,StaggeredGridLayoutManager.VERTICAL));
    recyclerView.addItemDecoration(new DividerGridItemDecoration(this));
    
    效果如下
    device-2018-11-21-003059.png
    瀑布流实现

    修改item_view.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"
        android:layout_margin="2dp"
        android:background="@android:color/white"
        android:orientation="vertical">
    
        <TextView
            android:id="@+id/tv_item"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:gravity="center"
            android:text="moon" />
    </LinearLayout>
    

    修改RecyclerViewActivity.java

    import android.content.Context;
    import android.os.Bundle;
    import android.support.annotation.NonNull;
    import android.support.annotation.Nullable;
    import android.support.v4.app.FragmentActivity;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.StaggeredGridLayoutManager;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.LinearLayout;
    import android.widget.TextView;
    import android.widget.Toast;
    
    import com.example.liudeshu.androidtest.util.DividerGridItemDecoration;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class RecyclerViewActivity extends FragmentActivity {
    
        RecyclerView recyclerView;
        
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.activity_recycleview);
    
            recyclerView = findViewById(R.id.recycerview);
    
    //        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    //        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
            recyclerView.setLayoutManager(new StaggeredGridLayoutManager(4,
                    StaggeredGridLayoutManager.VERTICAL));
            recyclerView.addItemDecoration(new DividerGridItemDecoration(this));
            recyclerView.setAdapter(new MyAdapter(this, getListData()));
        }
    
        private List<String> getListData() {
            List<String> dataSource = new ArrayList<>();
            for (int index = 0; index < 20; index++) {
                dataSource.add(String.valueOf(index));
            }
            return dataSource;
        }
    
        class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    
            Context mContext;
            List<String> mDataSource;
            List<Integer> mHeightSource;
    
            public MyAdapter(Context context, List<String> dataSource) {
                mContext = context;
                mDataSource = dataSource;
                mHeightSource = getItemDataHeight();
            }
    
            private List<Integer> getItemDataHeight() {
                List<Integer> heightSource = new ArrayList<Integer>();
                for (int i = 0; i < mDataSource.size(); i++) {
                    heightSource.add((int) (100 + Math.random() * 300));
                }
                return heightSource;
            }
    
            @NonNull
            @Override
            public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
                View itemView = LayoutInflater.from(mContext).inflate(R.layout.item_view, viewGroup, false);
                MyViewHolder myViewHolder = new MyViewHolder(itemView);
                return myViewHolder;
            }
    
            @Override
            public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, final int i) {
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) myViewHolder.valueTv.getLayoutParams();
                lp.height = mHeightSource.get(i);
                myViewHolder.valueTv.setLayoutParams(lp);
    
                myViewHolder.valueTv.setText(mDataSource.get(i));
                myViewHolder.valueTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(mContext, "这是第" + i + "项", Toast.LENGTH_SHORT).show();
                    }
                });
            }
    
            @Override
            public int getItemCount() {
                return mDataSource == null ? 0 : mDataSource.size();
            }
    
            class MyViewHolder extends RecyclerView.ViewHolder {
    
                TextView valueTv;
    
                public MyViewHolder(@NonNull View itemView) {
                    super(itemView);
    
                    valueTv = itemView.findViewById(R.id.tv_item);
                }
            }
        }
    }
    
    效果如下
    device-2018-11-21-004032.png

    相关文章

      网友评论

          本文标题:Android RecyclerView应用

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