安卓RecyclerView的简单实用

来源:互联网 发布:unity3d 角色资源 编辑:程序博客网 时间:2024/05/17 04:33

RecycleViewAndroid5.0的新特性,所以我们的最低版本如果小于5.0,就要添加依赖(兼容包)

简单的实现了添加,删除,list型,grid型,瀑布型

实现思路

1.继承RecycleView.adapter2.viewholder3.在继承RecyclerView.Adapter的类泛型定义为这个viewholder4.创建构造方法,得到外界的上下文,数据传到适配器中5.onCreateViewHolder方法中,创建布局view对象及viewholder对象6.MyViewHolder查找控件对象7.onBindViewHolder绑定数据
添加布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal">        <Button            android:id="@+id/btn_add"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_weight="1"            android:text="添加"            android:textAllCaps="false" />        <Button            android:id="@+id/btn_delete"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_weight="1"            android:text="删除"            android:textAllCaps="false" />        <Button            android:id="@+id/btn_list"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_weight="1"            android:text="List"            android:textAllCaps="false" />        <Button            android:id="@+id/btn_grid"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_weight="1"            android:text="Grid"            android:textAllCaps="false" />        <Button            android:id="@+id/btn_flow"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_weight="1"            android:text="flow"            android:textAllCaps="false" />    </LinearLayout>    <android.support.v7.widget.RecyclerView        android:id="@+id/recyclerview"        android:layout_width="match_parent"        android:layout_height="match_parent"/></LinearLayout>
创建一个新布局item_recyclerview.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:background="@android:color/white"    android:padding="5dp">    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:background="#22000000"        android:gravity="center"        android:orientation="horizontal"        android:padding="5dp">        <ImageView            android:id="@+id/iv_icon"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:src="@mipmap/ic_launcher" />        <TextView            android:id="@+id/tv_title"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginLeft="3dp"            android:text="Content"            android:textAllCaps="false"            android:textColor="#000000" />    </LinearLayout></RelativeLayout>
工具类

public class DividerListItemDecoration 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 DividerListItemDecoration(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) {//        Log.e("recyclerview - itemdecoration", "onDraw()");        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);            RecyclerView v = new 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);        }    }}
创建适配器

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.MyViewHolder>{    //通过构造函数得到外界的上下文及数据    private final Context context;    private ArrayList<String> datas;    public MyRecyclerViewAdapter(Context context, ArrayList<String> datas) {        this.context = context;        this.datas= datas;    }    //相当于getview方法,创建view对象及viewholder对象    @Override    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {        //把一个xml布局转为view对象        View itemView = View.inflate(context, R.layout.item_recyclerview, null);        //创建viewholder对象        MyViewHolder myViewHolder = new MyViewHolder(itemView);        //返回我们的viewholder即可        return myViewHolder;    }    //相当于getview绑定数据不符的代码,数据和view绑定    @Override    public void onBindViewHolder(MyViewHolder holder, int position) {        //根据item位置得到对应的数据        String data = datas.get(position);        //通过holder对象,给控件设置数据        holder.tv_title.setText(data);    }    class MyViewHolder extends RecyclerView.ViewHolder{        //控件对象        private ImageView iv_icon;        private TextView tv_title;        public MyViewHolder(View itemView) {            super(itemView);            iv_icon=(ImageView) itemView.findViewById(R.id.iv_icon);            tv_title=(TextView) itemView.findViewById(R.id.tv_title);        }    }    //C.RecycleView点击事件的接口    interface OnItemClickListener{        /**         * 抽象方法,RecycleView某个被点击的时候回调         * @param view   点击item对象         * @param data   点击时的数据         */        void onItemClick(View view,String data);    }    //C.创建接口    private OnItemClickListener mOnItemClickListener;    //C.设置RecycleView某个监听    public void setOnItemClickListener(OnItemClickListener onItemClickListener){        mOnItemClickListener=onItemClickListener;    }    //添加item    public void addData(int i, String name) {        datas.add(i,name);        notifyDataSetChanged();    }    //删除item    public void removeData(int i) {        datas.remove(i);        notifyDataSetChanged();    }    //决定了recycleView条目的数量    @Override    public int getItemCount() {        return datas.size();    }}
最后再MainActivity中实现

public class MainActivity extends AppCompatActivity implements View.OnClickListener {    private Button btn_add;    private Button btn_delete;    private Button btn_list;    private Button btn_grid;    private Button btn_flow;    private RecyclerView recyclerview;    private ArrayList<String> datas;    private MyRecyclerViewAdapter adapter;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //初始化方法        initView();        initData();        //B.设置recycleVIew的适配器        adapter = new MyRecyclerViewAdapter(this, datas);        recyclerview.setAdapter(adapter);        //B.设置布局管理器        recyclerview.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,false));        //B.设置点击事件        adapter.setOnItemClickListener(new MyRecyclerViewAdapter.OnItemClickListener() {            @Override            public void onItemClick(View view, String data) {                Toast.makeText(MainActivity.this,"点击了"+data,Toast.LENGTH_SHORT).show();            }        });        //C.添加RecycleView的分割线        recyclerview.addItemDecoration(new DividerListItemDecoration(this,DividerListItemDecoration.VERTICAL_LIST));        //C.设置默认动画,可以自定义        recyclerview.setItemAnimator(new DefaultItemAnimator());    }    private void initData() {        datas = new ArrayList<>();        //准备数据集合        for (int i = 0; i < 100; i++) {            datas.add("Content_" + i);        }    }    private void initView() {        btn_add = (Button) findViewById(R.id.btn_add);        btn_delete = (Button) findViewById(R.id.btn_delete);        btn_list = (Button) findViewById(R.id.btn_list);        btn_grid = (Button) findViewById(R.id.btn_grid);        btn_flow = (Button) findViewById(R.id.btn_flow);        recyclerview = (RecyclerView) findViewById(R.id.recyclerview);        //设置点击事件        btn_add.setOnClickListener(this);        btn_delete.setOnClickListener(this);        btn_list.setOnClickListener(this);        btn_grid.setOnClickListener(this);        btn_flow.setOnClickListener(this);    }    @Override    public void onClick(View view) {        switch (view.getId()) {            case R.id.btn_add://D.添加数据                adapter.addData(0,"同桌最帅");                break;            case R.id.btn_delete://D.删除数据                adapter.removeData(0);                //定位到指定的item                //recyclerview.scrollToPosition(55);                break;            case R.id.btn_list://设置List类型效果                recyclerview.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));                break;            case R.id.btn_grid://设置Grid类型效果                recyclerview.setLayoutManager(new GridLayoutManager(this,2,GridLayoutManager.VERTICAL,false));                break;            case R.id.btn_flow://设置瀑布流类型效果               recyclerview.setLayoutManager(new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL));                break;        }    }}

好了,这就简单的实现了我们RecyclerView的一些简单的使用!大家可以做一下!

原创粉丝点击