安卓基础知识Android开发经验谈Android进阶之路

RecyclerView的基本使用(一)

2016-08-11  本文已影响1467人  AmatorLee

生活本来就不容易,而我们的不努力只会让生活变得更加无赖

前几天依据《Android群英传》的学习写了一篇笔记是关于ListView的基本使用
但是Google已经推出了更加自由的RecyclerView取代ListView,所以这两天特地花时间学习了一下RecyclerView的基本用法,今天写的这篇将实现RecyclerView的基本功能如基本使用,添加分界线,拖拽移动,滑动删除等,过几天再接着学习更高级的功能,
整体预览:

整体

基本用法

我们知道RecyclerView是用以取代ListView和GridView的,所以依据后两者用法可知,RecyclerView必须要有一样东西,适配器Adapter, 而Adapter则需要数据项以及view填充

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#44ff00">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hello"
        android:textColor="#fff"
        android:textSize="40sp"
        android:layout_gravity="center_horizontal"
        android:gravity="center"
        android:id="@+id/text_view"/>
</LinearLayout>```
* activity_main.xml

<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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" tools:context="com.lqg.myrecyclerview.MainActivity">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:id="@+id/tool_bar"
app:title="RecyclerDemo"
app:titleTextColor="@android:color/white"
android:background="@color/colorPrimary">
</android.support.v7.widget.Toolbar>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/recycler_view">
</android.support.v7.widget.RecyclerView>
</LinearLayout>```

public class MyAadapter extends RecyclerView.Adapter{
    private LayoutInflater inflater;
    public List<String> list;
  
    public MyAadapter(Context context , List<String> list) {
        this.list = list;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(inflater.inflate(R.layout.item_viewholder,parent,false));
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        final ViewHolder viewHolder = (ViewHolder) holder;
        viewHolder.textview.setText(list.get(position));
    }

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

    private class ViewHolder extends RecyclerView.ViewHolder{

        private TextView textview;

        public ViewHolder(View itemView) {
            super(itemView);

            textview = (TextView) itemView.findViewById(R.id.text_view);
        }
    }
}```
MainActivity.java

public class MainActivity extends AppCompatActivity implements Toolbar.OnMenuItemClickListener {

private RecyclerView recyclerView;
private List<String> mDatas;
private MyAadapter myAadapter;
private MyAadapter.OnClickListener mOnClickListener;
private Toolbar mToolbar;
private RecyclerView.LayoutManager manager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mDatas = getList();
    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    myAadapter = new MyAadapter(this,mDatas);
    recyclerView.setAdapter(myAadapter);
    //Toolbar
    mToolbar = (Toolbar) findViewById(R.id.tool_bar);
    setSupportActionBar(mToolbar);
    mToolbar.setOnMenuItemClickListener(this);

}
//获取List方法
private List<String> getList(){
List<String> list = new ArrayList<String>();
for (int i = 'A';i<'z';++i){
list.add(""+(char)i);
}
return list;
}

其中需要注意的一点就是```setLayoutManager```这个方法是设置一个LayoutManager的.其中选项为LinearLayoutManager()线性),GridLayoutManager(网格)以及StaggerGridLayoutManager(瀑布流)三种
效果

![linearLayout.gif](https://img.haomeiwen.com/i2605454/4c18264dd6588683.gif?imageMogr2/auto-orient/strip)

![grid.gif](https://img.haomeiwen.com/i2605454/8ba54cceab1f52c5.gif?imageMogr2/auto-orient/strip)

![stagger.gif](https://img.haomeiwen.com/i2605454/125c6e07fc3f4c0f.gif?imageMogr2/auto-orient/strip)
就问你一句,丑不丑!不过没关系,丑是因为它有变炫的资本,下面添加分割线
#### 分割线
想要理解分割线的概念,首先得新建类实现```RecyclerView.ItemDecoration```;接着理解几个简单的概念,不过一幅图就能解决的事尽量憋说话

![Paste_Image.png](https://img.haomeiwen.com/i2605454/74568052f8c85b24.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

下面从代码张进一步理解
* LinearLayout的分割线类:DividerItemDecolation.java

public class DividerItemDecpration extends RecyclerView.ItemDecoration{

/**
 * 巧妙利用系统自带,可定制
 */
private final  static  int[] ATTRS = {android.R.attr.listDivider};
/**
 * 获取布局走向
 */
private final static int ORIENTETION_VERTIVAL = LinearLayoutManager.VERTICAL;
private  final static int ORIENTATION_HORIZONTAL =LinearLayoutManager.HORIZONTAL;
private Drawable mDivider;
private int mOrientation;

/**
 * 构造方法,获取系统属性,猴设置布局走向
 */
public DividerItemDecpration(Context context ,int Orientation) {
    TypedArray ta = context.obtainStyledAttributes(ATTRS);
    mDivider = ta.getDrawable(0);
    ta.recycle();
    setOrientation(Orientation);
}

/**
 * 设置布局走向方法
 */
private void setOrientation(int Orientation){
    if (mOrientation !=ORIENTETION_VERTIVAL && mOrientation != ORIENTATION_HORIZONTAL)
        throw new IllegalArgumentException("Error Orientation");
    mOrientation = Orientation;
}
/**
 * 要画分割线必须得有画布
 * onDraw方法
 */
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
    if (mOrientation == ORIENTETION_VERTIVAL){
        drawVertical(c,parent);
    }else{
        drawHorizontal(c,parent);
    }

}
/**
 * 横向
 */

private void drawHorizontal(Canvas c, RecyclerView parent) {
    //回去父布局的顶部内间距为top
    final int top = parent.getPaddingTop();
    //由图可知,利用parent的高度减去底部内间距为底
    final int buttom = 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 rl = (RecyclerView.LayoutParams) child.getLayoutParams();
        //获取子布局的最右位置+右外间距为右
        final int left = child.getRight() + rl.rightMargin;
        final int right = left + mDivider.getIntrinsicHeight();
        mDivider.setBounds(left,top,right,buttom);
        mDivider.draw(c);
    }
}

private void drawVertical(Canvas c, RecyclerView parent) {
    //parent的左内间距为左
    final int left = parent.getPaddingLeft();
    //parent宽度减去parent的right为右
    final int right = parent.getWidth()- parent.getRight();
    final int childCount = parent.getChildCount();
    for (int i = 0 ; i <childCount ;++i){
        final View child = parent.getChildAt(i);
        final RecyclerView recyclerView = new RecyclerView(parent.getContext());
        final RecyclerView.LayoutParams rl = (RecyclerView.LayoutParams) child.getLayoutParams();
        final int top = child.getBottom() + rl.bottomMargin;
        final int buttom = top + mDivider.getIntrinsicHeight();
        mDivider.setBounds(left,top,right,buttom);
        mDivider.draw(c);
    }
}

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    if (mOrientation == ORIENTETION_VERTIVAL){
        outRect.set(0,0,0,mDivider.getIntrinsicHeight());
    }else{
        outRect.set(0,0,mDivider.getIntrinsicWidth(),0);
    }
}

}```

linear.gif

添加点击方法

除了分割线有点坑爸爸之外,还有就是并没有点击方法的API,所以需要我们自己定制,我们可以在适配器里写我们的方法给MainActivity调用,代码如下:
MyAdapter.java

public class MyAadapter extends RecyclerView.Adapter{
    private LayoutInflater inflater;
    public List<String> list;
    private OnClickListener mOnItemClickListener;

    /**
     * 回调
     */
    public interface OnClickListener{
        public void OnClick(View view,int position);
        public boolean OnLongClick(RecyclerView.ViewHolder viewHolder,View view,int position);
    }

    public void setOnItemClick(OnClickListener mOnItemClickListener){
        this.mOnItemClickListener = mOnItemClickListener;

    }

    public MyAadapter(Context context , List<String> list) {
        this.list = list;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(inflater.inflate(R.layout.item_viewholder,parent,false));
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        final ViewHolder viewHolder = (ViewHolder) holder;
        viewHolder.textview.setText(list.get(position));

        //监听回调
        if (mOnItemClickListener != null){
           viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   int pos = viewHolder.getPosition();
                   mOnItemClickListener.OnClick(viewHolder.itemView,pos);
               }
           });
            viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    int pos = viewHolder.getPosition();
                    mOnItemClickListener.OnLongClick(viewHolder,viewHolder.itemView,pos);
                    return false;
                }
            });
        }

    }

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

    private class ViewHolder extends RecyclerView.ViewHolder{

        private TextView textview;

        public ViewHolder(View itemView) {
            super(itemView);

            textview = (TextView) itemView.findViewById(R.id.text_view);
        }
    }
}```
MainActivity.java
只需在MainActivity中用Adapter调用方法即可

myAadapter.setOnItemClick(new MyAadapter.OnClickListener() {
@Override
public void OnClick(View view, int position) {
Toast.makeText(MainActivity.this,(position+1)+"onclick",Toast.LENGTH_SHORT).show();
}

        @Override
        public boolean OnLongClick(RecyclerView.ViewHolder viewHolder,
                                   View view, int position) {
            Toast.makeText(MainActivity.this,(position + 1)+"onLongClick",Toast.LENGTH_SHORT).show();
            if (position != mDatas.size()-1){
                helper.startDrag(viewHolder);
            }
            return false;
        }
    });```

效果

click.gif

基本拓展

如果RecyclerView只是这样的我选择狗带,但事实肯定不是,不然Google不可能花2W多行代码实现RecyclerView.下面开始展示他优秀的小功能

  1. 动态添加移除
    以往在ListView我们要添加一项或者移除一项Item,有点难度,不过RecyclerView让你一步到站,查看文档可以发现RecyclerView.Adapter利用两个方法notifyItemInserted(position);,notifyItemRemoved(position);,就是这两个让我们一步实现添加移除,我们可以简单封装在我们的适配器Adapter里,利用Toolbar定制两个菜单项实现点击添加移除
    Menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:title="@string/add"
        android:id="@+id/id_btn_add"
        app:showAsAction="ifRoom"
        android:orderInCategory="80" />
    <item
        android:title="@string/remove"
        android:id="@+id/id_btn_remove"
        app:showAsAction="ifRoom"
        android:orderInCategory="90" />
</menu>```
MyAdapter.java

public void insertOne(int position){
list.add("Insert One");
notifyItemInserted(position);
}

public void removeOne(int position){
    list.add("remove One");
    notifyItemRemoved(position);
}```

效果

add.gif

2.拖拽及侧滑删除
这个就是这两天学习最酷的一个功能,它的实现竟然也很简单,只需利用ItemTouchHelper这个帮助类即可,新建一个对象可以发现,它需要一个CallBack参数,所以我们写一个类扩展自ItemTouchHelper.Callback
MyCallBack.java

public class MyCallBack extends ItemTouchHelper.Callback{


    private List<String> mDatas;
    private MyAadapter adapter;

    public MyCallBack(MyAadapter adapter) {
        this.adapter = adapter;
        this.mDatas = adapter.list;
    }

    /**
     * 此方法用以设置是否响应拖拽或滑动事件,并且确定类型
     */
    @Override
    public int getMovementFlags(RecyclerView recyclerView,
                                RecyclerView.ViewHolder viewHolder) {

        final int dragFlags ,swipFlags;
        /**
         * 网格方向有UP ,Down ,left,right四个方向
         */
        if (recyclerView.getLayoutManager() instanceof GridLayoutManager){
            dragFlags= ItemTouchHelper.UP|
                    ItemTouchHelper.DOWN|ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT;
            swipFlags = 0;
        }else{
            //LineaLayout只有Up ,Down
             dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            //右滑删除
             swipFlags =  ItemTouchHelper.END;
        }

        return makeMovementFlags(dragFlags,swipFlags);
    }

    @Override
    public boolean onMove(RecyclerView recyclerView,
                          RecyclerView.ViewHolder viewHolder,
                          RecyclerView.ViewHolder target) {
        int framPosition = viewHolder.getAdapterPosition();
        int toPosition = target.getAdapterPosition();
        /**
         * 向上拖拽
         */
        if (framPosition > toPosition){
            for (int i = framPosition ;i < toPosition;++i){
                Collections.swap(mDatas,i,i+1);
            }
            /**
             * 向下拖拽
             */
        }else {
            for (int i = framPosition ;i > toPosition ;++i){
                Collections.swap(mDatas,i,i-1);
            }
        }
        adapter.notifyItemMoved(framPosition,toPosition);
        return true;
    }

    /**
     * viewHolder
     * params direction表示滑动方向,此处我们在上面规定为右滑
     */
    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        int position  = viewHolder.getAdapterPosition();
        adapter.notifyItemRemoved(position);
        adapter.list.remove(position);
    }

    /**
     * 是否长按拖拽
     */
    @Override
    public boolean isLongPressDragEnabled() {
        return false;
    }
}```
接着在MainActivity中我们之前定制的长按事件中利用ItemTouchHelper的```startDrag(viewHolder)```实现长按拖拽滑动删除,代码如下
``` /**
         * 拖拽事件
         */
        final ItemTouchHelper helper = new ItemTouchHelper(new MyCallBack(myAadapter));
        helper.attachToRecyclerView(recyclerView);
        myAadapter.setOnItemClick(new MyAadapter.OnClickListener() {
            @Override
            public void OnClick(View view, int position) {
                Toast.makeText(MainActivity.this,(position+1)+"onclick",Toast.LENGTH_SHORT).show();
            }

            @Override
            public boolean OnLongClick(RecyclerView.ViewHolder viewHolder,
                                       View view, int position) {
                Toast.makeText(MainActivity.this,(position + 1)+"onLongClick",Toast.LENGTH_SHORT).show();
                if (position != mDatas.size()-1){
                    helper.startDrag(viewHolder);
                }
                return false;
            }
        });```
效果

![drag.gif](https://img.haomeiwen.com/i2605454/60ab91d0610e7db9.gif?imageMogr2/auto-orient/strip)
如果这样简单的实现这么酷的功能还没爱上它,没关系接下来的学习将会更加炫酷

##### 如果你觉得本文有所错漏,麻烦指出,相互交流共同进步.
上一篇下一篇

猜你喜欢

热点阅读