RecyclerView封装详解完美用法一

原创 2016年05月30日 16:06:25

通过对RecyclerView的了解,个人认为此控件适用于需要listview与GridView切换的界面以及瀑布流界面。

第一篇主要是listView与Gridview切换代码:

一、先上RecyclerView的通用ViewHolder:

package com.example.recyclerview;

import android.graphics.Bitmap;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by 11981 on 2016/5/30.
 * RecyclerView通用ViewHolder
 */
public class MyViewHolder extends RecyclerView.ViewHolder {
    private SparseArray<View> mViews;
    public MyViewHolder(View itemView) {
        super(itemView);
        mViews= new SparseArray<View>();
    }

    //通过viewId获取控件
    public <T extends View> T getView(int viewId) {

        View view = mViews.get(viewId);
        if (view == null) {
            view = itemView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }
    /**
     * 设置TextView的值
     */
    public MyViewHolder setText(int viewId,String text){
        TextView tv= getView(viewId);
        tv.setText(text);
        return this;
    }
    public MyViewHolder setImageResource(int viewId,int resId){
        ImageView view= getView(viewId);
        view.setImageResource(resId);
        return this;
    }
    public MyViewHolder setImageBitamp(int viewId,Bitmap bitmap){
        ImageView view= getView(viewId);
        view.setImageBitmap(bitmap);
        return this;
    }
    public MyViewHolder setImageURI(int viewId,String uri){
        ImageView view= getView(viewId);
//        Imageloader.getInstance().loadImg(view,uri);
        return this;
    }
}
二、然后是适配器:

package com.example.recyclerview;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.List;

/**
 * Created by 11981 on 2016/5/26.
 * recyclerview_list_grid适配器
 */
public abstract class SimpleAdapters extends RecyclerView.Adapter<MyViewHolder> {

    private LayoutInflater mInflater;
    public List<DataDTO> mDatas;
    private int mlayoutId;

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

        void onItemLongClick(View view, int position);
    }

    private OnItemClickListener onItemClickListener;

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.onItemClickListener = listener;
    }

    public SimpleAdapters(Context context, List<DataDTO> datas, int layoutId) {
        this.mDatas = datas;
        this.mlayoutId = layoutId;
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public int getItemCount() {
        return mDatas.size();
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {
        convert(holder,mDatas.get(position));
        setUpItemEvent(holder);
    }
    public abstract  void convert(MyViewHolder holder,DataDTO datadto);

    public void setUpItemEvent(final MyViewHolder holder) {
        if (onItemClickListener != null) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //这个获取位置的方法,防止添加删除导致位置不变
                    int layoutPosition = holder.getAdapterPosition();
                    onItemClickListener.onItemClick(holder.itemView, layoutPosition);

                }
            });
            //longclick
            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    int layoutPosition = holder.getAdapterPosition();
                    onItemClickListener.onItemLongClick(holder.itemView, layoutPosition);
                    return false;
                }
            });
        }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        MyViewHolder viewHolder = new MyViewHolder(mInflater.inflate(mlayoutId, parent, false));
        return viewHolder;
    }

    public void addData(int pos,DataDTO datas) {
        mDatas.add(pos, datas);
        notifyItemInserted(pos);
    }

    public void deleteData(int pos) {
        mDatas.remove(pos);
        notifyItemRemoved(pos);
    }
}
三、最后是主类:

package com.example.recyclerview;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * recyclerview_list_grid主类
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private RecyclerView mRecyclerView;
    private List<DataDTO> mDatas;
    private SimpleAdapters mAdapter;

    private TextView mlist, mgrid, mhgrid, mstag,madd,mdel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initDatas();
        initViews();
        mAdapter=new SimpleAdapters(this, mDatas, R.layout.item_single_view) {

            @Override
            public void convert(MyViewHolder holder, DataDTO datadto) {
                holder.setText(R.id.id_tv,datadto.getAaa()).setImageResource(R.id.id_img,datadto.getBbb());
            }
        };
        mRecyclerView.setAdapter(mAdapter);
        //设置recyclerview布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(linearLayoutManager);

        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        mAdapter.setOnItemClickListener(new SimpleAdapters.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Toast.makeText(MainActivity.this,"click:"+position,Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onItemLongClick(View view, int position) {
                Toast.makeText(MainActivity.this,"longclick:"+position,Toast.LENGTH_SHORT).show();
            }
        });
        //设置recycler的Item分割线
        //listview转gridview没有列的分割
       // mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
    }

    private void initDatas() {
        mDatas = new ArrayList<DataDTO>();
        DataDTO data=new DataDTO();
        for (int i = 0; i <20 ; i++) {
            data.setAaa("aaaaa");
            data.setBbb(R.drawable.ic_menu_delete);
            mDatas.add(data);
        }
    }

    private void initViews() {
        mRecyclerView = (RecyclerView) findViewById(R.id.id_recyclerview);

        mlist = (TextView) findViewById(R.id.action_listview);
        mlist.setOnClickListener(this);
        mgrid = (TextView) findViewById(R.id.action_gridview);
        mgrid.setOnClickListener(this);
        mhgrid = (TextView) findViewById(R.id.action_hor_gridview);
        mhgrid.setOnClickListener(this);
        mstag = (TextView) findViewById(R.id.action_staggered);
        mstag.setOnClickListener(this);
        madd=(TextView) findViewById(R.id.action_add);
        madd.setOnClickListener(this);
        mdel=(TextView) findViewById(R.id.action_delete);
        mdel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.action_listview:
                mRecyclerView.setLayoutManager(
                        new LinearLayoutManager(this)
                );
                break;
            case R.id.action_gridview:
                //二参为列数
                mRecyclerView.setLayoutManager(
                        new GridLayoutManager(this, 3)
                );
                break;
            case R.id.action_hor_gridview:
                //一参为行数
                mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager
                        (8, StaggeredGridLayoutManager.HORIZONTAL));
                break;
            case R.id.action_staggered:
                Intent intent =new Intent();
                startActivity(intent.setClass(this,StaggereGridLayoutActivity.class));
                break;
            case R.id.action_add:
                DataDTO datas = new DataDTO();
                datas.setAaa("Insert One");
                datas.setBbb(R.drawable.ic_menu_delete);
                mAdapter.addData(1,datas);
                break;
            case R.id.action_delete:
                mAdapter.deleteData(1);
                break;
            default:
                break;
        }
    }
}
四、RecyclerView依赖工具类

package com.example.recyclerview;

/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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;

/**
 * This class is from the v7 samples of the Android SDK. It's not by me!
 * <p/>
 * See the license above for details.
 * RecyclerView依赖工具类
 */
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)
   {
//    Log.v("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);
      }
   }
}
五、实体类:

package com.example.recyclerview;

/**
 * Created by 11981 on 2016/5/29.
 * 实体类
 */
public class DataDTO {
    private String aaa;
    private int bbb;

    public int getBbb() {
        return bbb;
    }

    public void setBbb(int bbb) {
        this.bbb = bbb;
    }

    public String getAaa() {

        return aaa;
    }

    public void setAaa(String aaa) {
        this.aaa = aaa;
    }
}
六、其它的代码:

drawable下:

divider_two.xml:这个是自定义的分割线(listview)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size android:height="4dp" />
    <gradient
        android:centerColor="#ff00ff00"
        android:endColor="#ffff0000"
        android:startColor="#ff0000ff"
        android:type="linear"/>
</shape>
item_bg.xml:点击效果

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true" android:drawable="@color/state_item_pressed"/>
     <item android:drawable="@color/state_item_normal"/>
</selector>
还有一张图片(自行设置)名称:ic_menu_delete.png

Layout下:

主类布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context="com.example.recyclerview.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/action_listview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textSize="25sp"
            android:layout_weight="1"
            android:text="list" />

        <TextView
            android:id="@+id/action_gridview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textSize="25sp"
            android:layout_weight="1"
            android:text="grid" />

        <TextView
            android:id="@+id/action_hor_gridview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textSize="25sp"
            android:layout_weight="1"
            android:text="hgrid" />

        <TextView
            android:id="@+id/action_staggered"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textSize="25sp"
            android:layout_weight="1"
            android:text="stag" />
        <TextView
            android:id="@+id/action_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textSize="25sp"
            android:layout_weight="1"
            android:text="add" />
        <TextView
            android:id="@+id/action_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textSize="25sp"
            android:layout_weight="1"
            android:text="del" />
    </LinearLayout>

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


</LinearLayout>
item布局:item_single_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@drawable/item_bg"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_margin="3dp"
    android:layout_height="72dp">
    <TextView
        android:id="@+id/id_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="测试数据"/>

    <ImageView
        android:id="@+id/id_img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>
values下:

color中:

<color name="state_item_pressed">#AAff0000</color>
<color name="state_item_normal">#44ff0000</color>
style中;

<item name="android:windowNoTitle">true</item>
<item name="android:windowActionBar">false</item>
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>



视频学习链接

学习不同的写法,网址链接

下一篇写RecyclerView实现瀑布流。


相关文章推荐

Delphi7高级应用开发随书源码

  • 2003年04月30日 00:00
  • 676KB
  • 下载

android recyclerview adaper封装

关于Recyclerview,是比较好用的一个控件,代替了listview和gridview,灵活性比较强。基础的就不说了,我要讲的是如何封装一个基类的recyclerview adaper 代码:...

RecyclerView.Adapter的封装之路

封装后的用法:原始的Adapter单布局的Adapter多布局-单实体的Adapter多布局-多实体的Adapter多布局-多实体-多列的Adapter具体的封装过程:1-SingleAdapter:...

真实项目运用-RecyclerView封装

原文链接:从零开始搭建android框架系列 项目地址:MVPCommon 前言很久没有发表从零开始搭建android框架系列这个系列的文章了 。由于最近工作确实有点忙碌,也在脚踏实地的花时间研...

Android UltimateRecyclerView优雅地使用RecyclerView

前言:大家都在更青睐于使用RecyclerVIew来替代ListView,但是在使用的时候我们会发现ListView的一些常用方法在RecyclerView中没有,比如添加头部、尾部。而且在刷新加载方...

为RecyclerView打造通用Adapter 让RecyclerView更加好用

转载请标明出处: http://blog.csdn.net/lmj623565791/article/details/47251585; 本文出自:【张鸿洋的博客】 一、概述记得好久以前针...

RecyclerView Adapter简单封装

前言       今天是新年第一天,本来打算在上一年的最后一天写下来的,但是由于玩的时间长了一点,所以今天才写,算是在新的一年开一个好头,新年新气象嘛!       至于为什么要写这个文章呐!由于项目...

RecyclerView封装Adapter之添加头部和底部视图

RecyclerView封装Adapter之添加头部和底部视图在ListView中已经自带了添加头布局和添加底部布局的方法,但是在RecyclerView中,却没有默认实现,这导致在实现一些特殊布局中...
  • lisdye2
  • lisdye2
  • 2016年09月26日 22:13
  • 1885

RecyclerView多种布局封装优化(雷惊风)

今天看见一篇文章,讲到了RecyclerView一些关于加载多种布局样式时通常用法存在的一些问题,下面是文章地址:http://www.jianshu.com/p/c6a44e18badb 这里先看一...

RecyclerView用法(一)------展示多种类型Item数据

一、多Item布局实现(MultipleItem) 如果之前你用过ListView实现过此功能,那么你一定对下面这两个方法并不陌生@Override public int getItemVi...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:RecyclerView封装详解完美用法一
举报原因:
原因补充:

(最多只允许输入30个字)