博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
RecyclerView的基本使用(一)
阅读量:6216 次
发布时间:2019-06-21

本文共 12210 字,大约阅读时间需要 40 分钟。

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

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

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

  • item_viewholder.xml
```* activity_main.xml复制代码

<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> ```

  • 基本实现 MyAdapter.java
public class MyAadapter extends RecyclerView.Adapter{    private LayoutInflater inflater;    public List
list; public MyAadapter(Context context , List
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
mDatas;private MyAadapter myAadapter;private MyAadapter.OnClickListener mOnClickListener;private Toolbar mToolbar;private RecyclerView.LayoutManager manager;@Overrideprotected 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 getList(){ List list = new ArrayList(); for (int i = 'A';i<'z';++i){ list.add(""+(char)i); } return list; }

其中需要注意的一点就是```setLayoutManager```这个方法是设置一个LayoutManager的.其中选项为LinearLayoutManager()线性),GridLayoutManager(网格)以及StaggerGridLayoutManager(瀑布流)三种效果![linearLayout.gif](http://upload-images.jianshu.io/upload_images/2605454-4c18264dd6588683.gif?imageMogr2/auto-orient/strip)![grid.gif](http://upload-images.jianshu.io/upload_images/2605454-8ba54cceab1f52c5.gif?imageMogr2/auto-orient/strip)![stagger.gif](http://upload-images.jianshu.io/upload_images/2605454-125c6e07fc3f4c0f.gif?imageMogr2/auto-orient/strip)就问你一句,丑不丑!不过没关系,丑是因为它有变炫的资本,下面添加分割线#### 分割线想要理解分割线的概念,首先得新建类实现```RecyclerView.ItemDecoration```;接着理解几个简单的概念,不过一幅图就能解决的事尽量憋说话![Paste_Image.png](http://upload-images.jianshu.io/upload_images/2605454-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方法 */@Overridepublic 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 

}```

  • 使用方法很简答,只需调用addItemDecolation方法即可 效果

  • 如果想更炫的效果可以自己定制以及其他两个效果,在这里就不演示了

添加点击方法

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

public class MyAadapter extends RecyclerView.Adapter{    private LayoutInflater inflater;    public List
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
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;        }    });```复制代码

效果

基本拓展

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

  1. 动态添加移除 以往在ListView我们要添加一项或者移除一项Item,有点难度,不过RecyclerView让你一步到站,查看文档可以发现RecyclerView.Adapter利用两个方法notifyItemInserted(position);,notifyItemRemoved(position);,就是这两个让我们一步实现添加移除,我们可以简单封装在我们的适配器Adapter里,利用Toolbar定制两个菜单项实现点击添加移除 Menu.xml
```MyAdapter.java复制代码

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

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

效果

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

public class MyCallBack extends ItemTouchHelper.Callback{    private List
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](http://upload-images.jianshu.io/upload_images/2605454-60ab91d0610e7db9.gif?imageMogr2/auto-orient/strip)如果这样简单的实现这么酷的功能还没爱上它,没关系接下来的学习将会更加炫酷##### 如果你觉得本文有所错漏,麻烦指出,相互交流共同进步.复制代码

转载地址:http://ofmja.baihongyu.com/

你可能感兴趣的文章
【C#学习笔记】获得本机IP
查看>>
Azure ARM (17) 基于角色的访问控制 (Role Based Access Control, RBAC) - 自定义Role
查看>>
Windows Mobile下native c++ typeid的使用
查看>>
用ASP.NET写个SQLSERVER的小工具
查看>>
dojo 官方翻译 dojo/string 版本1.10
查看>>
flex for循环
查看>>
生活中的经典感人语句
查看>>
JavaScript常用字符串函数
查看>>
数据交换格式XML和JSON对比
查看>>
强烈推荐Oracle的入门心得
查看>>
POJ 1195 Mobile phones (二维树状数组或线段树)
查看>>
LINUX下使用crontab进行RMAN备份实验
查看>>
Hive文件格式
查看>>
[LeetCode] Delete Node in a Linked List
查看>>
农历js脚本
查看>>
获取对象的 RTTI 属性与事件的函数
查看>>
java获得CPU使用率,系统内存,虚拟机内存等情况
查看>>
.NET操作Excel表格的整理
查看>>
vcl.Forms等与VCL界面有关的单元不支持跨平台
查看>>
Windows Vista for Developers——第一部分:Aero向导
查看>>