美文网首页
RecyclerView使用

RecyclerView使用

作者: 宁静世界 | 来源:发表于2016-11-16 22:47 被阅读0次

    主要包含

    1,多条目
    2,点击事件与屏蔽
    3,条目动画
    4,分割线

    实现效果如下图


    Paste_Image.png

    第一步

    添加依赖

    compile 'com.android.support:recyclerview-v7:23.1.1'
    

    第二步

    在布局activity_main.xml中添加RecyclerView控件

    <?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:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.boatt.recylerview.MainActivity">
    
        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>
    </RelativeLayout>
    

    第三步

    创建条目布局

    recyclerview_item1.xml

    <?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="match_parent">
    <TextView
        android:background="@android:color/holo_green_light"
        android:padding="20dp"
        android:id="@+id/item_text"
        android:text="我是条目1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    </LinearLayout>
    

    recyclerview_item2.xml

    <?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="match_parent">
    <TextView
        android:background="@android:color/holo_green_light"
        android:padding="20dp"
        android:id="@+id/item_text"
        android:text="我是条目2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    </LinearLayout>
    

    第四步

    在activity中开始使用RecyclerView

    MainActivity.java

    package com.boatt.recylerview;
    
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.DefaultItemAnimator;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.view.View;
    
    import com.boatt.recylerview.adaper.RecyclerViewAdapter;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity {
       public  RecyclerView mRecyclerView;
        protected List<String> mData;//数据
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
            //设置RecyclerView的布局管理
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
            mRecyclerView.setLayoutManager(linearLayoutManager);
            mRecyclerView.setItemAnimator(new DefaultItemAnimator());//设置动画
            initData();
            final RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, mData);
            mRecyclerView.setAdapter(adapter);//设置适配器
            adapter.setmOnItemClickListener(new RecyclerViewAdapter.OnItemClickListener() {//设置点击事件
                @Override
                public void onItemClickListener(View view, int position) {
                    adapter.add(position);
                }
    
                @Override
                public void onItemLongClickListener(View view, int position) {
                    adapter.delete(position);
                }
            });
            //添加我们自定义的分隔线
             mRecyclerView.addItemDecoration(new MyDecoration(this, MyDecoration.VERTICAL_LIST));
        }
    
        /**
         * 初始化数据
         */
        private void initData() {
            mData = new ArrayList<>();
            for (int i = 0; i < 60; i++) {
                mData.add("我是条目"+i);
            }
        }
    }
    

    第五步

    为RecyclerView创建适配器

    RecyclerViewAdapter.java

    package com.boatt.recylerview.adaper;
    
    import android.content.Context;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    import com.boatt.recylerview.R;
    import com.boatt.recylerview.holder.MyViewHolder1;
    import com.boatt.recylerview.holder.MyViewHolder2;
    
    import java.util.List;
    
    /**
     * Created by Administrator on 2016/11/16.
     */
    public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
        /**
         * 条目1
         */
        private static final int ITEM1 = 1;
        /**
         * 条目2
         */
        private static final int ITEM2 = 2;
        private Context mContext;//上下文
        protected List<String> mData;//数据
        private LayoutInflater mInflater;
    
        /**
         * 点击事件的接口
         */
        public interface  OnItemClickListener{
            void onItemClickListener(View view, int position);//点击
            void onItemLongClickListener(View view,int position);//长按
        }
        private OnItemClickListener mOnItemClickListener;
    
        public void setmOnItemClickListener(OnItemClickListener mOnItemClickListener) {
            this.mOnItemClickListener = mOnItemClickListener;
        }
    
        @Override
        public int getItemViewType(int position) {
            return position%2==0?ITEM1:ITEM2;
        }
    
        /**
         * 构造函数
         * @param context
         * @param datas
         */
        public RecyclerViewAdapter(Context context,List<String> datas) {
            this.mContext=context;
            this.mData=datas;
            mInflater=LayoutInflater.from(context);
    
        }
    
        /**
         * 必须实现的方法
         * @return
         */
        @Override
        public int getItemCount() {
            return mData.size();
        }
    
        private static final String TAG = "RecyclerViewAdapter";
        /**
         * 创建一个ViewHolder
         * @param parent
         * @param viewType
         * @return
         */
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if(viewType == ITEM1){
                View view=mInflater.inflate(R.layout.recyclerview_item1,parent,false);//得到item的布局
                MyViewHolder1 viewHolder=new MyViewHolder1(view);
                return  viewHolder;
            }else{
                View view=mInflater.inflate(R.layout.recyclerview_item2,parent,false);//得到item的布局
                MyViewHolder2 viewHolder=new MyViewHolder2(view);
                return  viewHolder;
            }
        }
    
        /**
         * 绑定数据ViewHolder里面的数据
         * @param holder
         * @param position
         */
    
        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
            if(holder instanceof MyViewHolder1){
                MyViewHolder1 holder1 =  (MyViewHolder1)holder;
                holder1.item_text.setText(mData.get(position));
                setUpItemEvent(holder1);
                return;
            }else if(holder instanceof MyViewHolder2){
                MyViewHolder2 holder2 =  (MyViewHolder2)holder;
                holder2.item_text.setText(mData.get(position));
                return ;
            }
        }
    
        /**
         * 实现点击事件
         * @param holder
         */
        protected void setUpItemEvent(final MyViewHolder1 holder) {
            if (mOnItemClickListener!=null){
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int layoutPosition = holder.getLayoutPosition();
                        mOnItemClickListener.onItemClickListener(holder.itemView,layoutPosition);
                    }
                });
                holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        int layoutPosition=holder.getLayoutPosition();
                        mOnItemClickListener.onItemLongClickListener(holder.itemView,layoutPosition);
                        return false;
                    }
                });
            }
        }
    
        /**
         * 添加
         * @param position
         */
        public void add(int position){
            mData.add(position,"position");
            notifyItemInserted(position);
    
        }
    
        /**
         * 删除
         * @param position
         */
        public void delete(int position){
            mData.remove("position");
            notifyItemRemoved(position);
        }
    }
    

    第六步

    创建Holder,分别有两个

    MyViewHolder1 .java

    package com.boatt.recylerview.holder;
    
    import android.support.v7.widget.RecyclerView;
    import android.view.View;
    import android.widget.TextView;
    
    import com.boatt.recylerview.R;
    
    /**
     * Holder
     */
    public
    class MyViewHolder1 extends RecyclerView.ViewHolder{
    
        public TextView item_text;
        public MyViewHolder1(View itemView) {
            super(itemView);
            item_text= (TextView) itemView.findViewById(R.id.item_text);
        }
    }
    

    MyViewHolder2 .java

    package com.boatt.recylerview.holder;
    
    import android.support.v7.widget.RecyclerView;
    import android.view.View;
    import android.widget.TextView;
    
    import com.boatt.recylerview.R;
    
    /**
     * Holder
     */
    public class MyViewHolder2 extends RecyclerView.ViewHolder{
    
        public TextView item_text;
        public MyViewHolder2(View itemView) {
            super(itemView);
            item_text= (TextView) itemView.findViewById(R.id.item_text);
        }
    }
    

    第七步

    创建分割线

    MyDecoration .java

    package com.boatt.recylerview;
    
    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;
    
    /**
     * Created by Administrator on 2016/11/16.
     */
    public class MyDecoration 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 MyDecoration(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);
            }
        }
    }
    

    第八步

    自定义分割线
    在drawable文件夹下面

    divider.xml

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle" >
    
        <solid android:color="#fff"/>
        <size android:height="5dp"/>
    
    </shape>
    

    第九步

    为当前主题应用该分割线
    在values文件夹中

    values/styles.xml

    <resources>
    
        <!-- Base application theme. -->
        <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
            <!-- Customize your theme here. -->
            <item name="colorPrimary">@color/colorPrimary</item>
            <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
            <item name="colorAccent">@color/colorAccent</item>
            <item name="android:listDivider">@drawable/divider</item>
        </style>
    
    </resources>

    相关文章

      网友评论

          本文标题:RecyclerView使用

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