安卓中最常用的控件就是RecylerView了,当然除了H5布局之外。RecyclerView是Android 5.0推出的,是support-v7包中的新组件,它被用来代替ListView和GridView,并且能够实现瀑布流的布局,更加高级并且更加灵活,提供更为高效的回收复用机制,同时实现管理与视图的解耦合。
简介
- 定义
Google
用于代替ListView
的滑动组件 - 特点:功能更强大、支持定制样式更丰富、扩展性更高
与ListView对比
优缺点
RecyclerView实现控制点击、长按事件较为麻烦,需要自己写,但更自由!
应用场景
列表页展示界面(需扩展、需支持动画、频繁更新 & 局部刷新)
基础概念
RecyclerView.Adapter
和ListView一样,RecyclerView一样需要适配器,而且这个适配器强制要求了我们必须要用Viewholder,让性能得到优化,而且getView方法不需自己写,我们只需要写好Viewholder,View的复用已经封装好了。
LayoutManager
布局管理器,设置为LinearLayoutManager、GridLayoutManager、StaggeredGridLayoutManager可以轻易地实现ListView,GridView以及流式布局的列表效果。
还可管理滚动 & 循环利用
ItemAnimator
这个类可以实现增删动画,而且不想设置的话它的默认效果已经很好了。
使用步骤
- 定义主xml布局
- 根据需要定义RecyclerView每行所实现的xml布局
- 定义一个Adapter类继承RecyclerView.Adapter,重写里面的方法。
- 定义一个HashMap构成的列表,将数据以键值对的方式存放在里面。
- 构造Adapter对象,设置适配器。
- 将RecyclerView绑定到Adapter上。
实例演示
定义主xml布局activity_main.xml
<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" tools:context="${relativePackage}.${activityClass}" > <android.support.v7.widget.RecyclerView android:id="@+id/my_recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" android:scrollbars="horizontal" /><!--设置一个RecyclerView--> </RelativeLayout>
引入支持包
compile 'com.android.support:recyclerview-v7:23.1.1'
定义RecyclerView每行所实现的xml布局(item布局)list_cell.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"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_alignParentRight="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ItemImage"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Text" android:id="@+id/Itemtitle" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Text" android:id="@+id/Itemtext" android:layout_below="@+id/Itemtitle"/> </RelativeLayout> </LinearLayout>
定义一个Adapter类继承 RecyclerView.Adapter,重写里面的方法。MyAdapter.java
package scut.receiverview; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.HashMap; /** * Created by yany on 2016/4/11. */ public class MyAdapter extends RecyclerView.Adapter { private LayoutInflater inflater; private ArrayList<HashMap<String, Object>> listItem; private MyItemClickListener myItemClickListener; public MyAdapter(Context context, ArrayList<HashMap<String, Object>> listItem) { inflater = LayoutInflater.from(context); this.listItem = listItem; }//构造函数,传入数据 //定义Viewholder class Viewholder extends RecyclerView.ViewHolder { private TextView Title, Text; private ImageView ima; public Viewholder(View root) { super(root); Title = (TextView) root.findViewById(R.id.Itemtitle); Text = (TextView) root.findViewById(R.id.Itemtext); ima = (ImageView) root.findViewById(R.id.ItemImage); root.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (myItemClickListener != null) myItemClickListener .onItemClick(v,getPosition()); } }//监听到点击就回调MainActivity的onItemClick函数 ); } public TextView getTitle() { return Title; } public TextView getText() { return Text; } public ImageView getIma() { return ima; } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new Viewholder(inflater.inflate(R.layout.list_cell, null)); }//在这里把ViewHolder绑定Item的布局 @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { Viewholder vh = (Viewholder) holder; vh.Title.setText((String) listItem.get(position).get("ItemTitle")); vh.Text.setText((String) listItem.get(position).get("ItemText")); vh.ima.setImageResource((Integer) listItem.get(position).get("ItemImage")); }//在这里绑定数据到ViewHolder里面 @Override public int getItemCount() { return listItem.size(); }//返回Item数目 public void setOnItemClickListener(MyItemClickListener listener){ myItemClickListener = listener; }//绑定MainActivity传进来的点击监听器 }
实现点击事件
在Viewholder里面设置了点击事件监听器
通过调用OnItemClickListener的接口方法回调MainActivity里的方法。
MyItemClickListener.java接口:用来实现点击事件
package scut.receiverview; import android.view.View; public interface MyItemClickListener { public void onItemClick(View view,int postion); }
在MainActicity.java里:
- 定义一个HashMap构成的列表,将数据以键值对的方式存放在里面。
- 构造Adapter对象,设置适配器
- 将RecyclerView绑定到Adapter上
MainActicity.java
package scut.receiverview; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends AppCompatActivity implements MyItemClickListener { private RecyclerView Rv; private ArrayList<HashMap<String,Object>> listItem; private MyAdapter myAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initData(); initView(); } public void initData(){ listItem = new ArrayList<HashMap<String, Object>>();/*在数组中存放数据*/ for (int i = 0; i < 100; i++) { HashMap<String, Object> map = new HashMap<String, Object>(); map.put("ItemTitle", "第" + i + "行"); map.put("ItemText", "这是第" + i + "行"); map.put("ItemImage",R.mipmap.ic_launcher); listItem.add(map); } } public void initView(){ Rv = (RecyclerView) findViewById(R.id.my_recycler_view); //使用线性布局 LinearLayoutManager layoutManager = new LinearLayoutManager(this); Rv.setLayoutManager(layoutManager); Rv.setHasFixedSize(true); Rv.addItemDecoration(new DividerItemDecoration(this, layoutManager.getOrientation()));//用类设置分割线 //Rv.addItemDecoration(new DividerItemDecoration(this, R.drawable.list_divider)); //用已有图片设置分割线 //为ListView绑定适配器 myAdapter = new MyAdapter(this,listItem); myAdapter.setOnItemClickListener(this); Rv.setAdapter(myAdapter); } @Override public void onItemClick(View view, int postion) {//点击事件的回调函数 System.out.println("点击了第"+postion+"行"); Toast.makeText(this, (String)listItem.get(postion).get("ItemText"), Toast.LENGTH_SHORT).show(); } }
实现分割线ItemDecoration
DividerItemDecoration.java:
package scut.receiverview; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.TypedValue; import android.view.View; public class DividerItemDecoration extends RecyclerView.ItemDecoration { /* * RecyclerView的布局方向,默认先赋值 * 为纵向布局 * RecyclerView 布局可横向,也可纵向 * 横向和纵向对应的分割想画法不一样 * */ private int mOrientation = LinearLayoutManager.VERTICAL ; /** * item之间分割线的size,默认为1 */ private int mItemSize = 1 ; /** * 绘制item分割线的画笔,和设置其属性 * 来绘制个性分割线 */ private Paint mPaint ; /** * 构造方法传入布局方向,不可不传 * @param context * @param orientation */ public DividerItemDecoration(Context context,int orientation) { this.mOrientation = orientation; if(orientation != LinearLayoutManager.VERTICAL && orientation != LinearLayoutManager.HORIZONTAL){ throw new IllegalArgumentException("请传入正确的参数") ; } mItemSize = (int) TypedValue.applyDimension(mItemSize, TypedValue.COMPLEX_UNIT_DIP,context.getResources().getDisplayMetrics()); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG) ; mPaint.setColor(Color.BLUE); /*设置填充*/ mPaint.setStyle(Paint.Style.FILL); } @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { if(mOrientation == LinearLayoutManager.VERTICAL){ drawVertical(c,parent) ; }else { drawHorizontal(c,parent) ; } } /** * 绘制纵向 item 分割线 * @param canvas * @param parent */ private void drawVertical(Canvas canvas,RecyclerView parent){ final int left = parent.getPaddingLeft() ; final int right = parent.getMeasuredWidth() - parent.getPaddingRight() ; final int childSize = parent.getChildCount() ; for(int i = 0 ; i < childSize ; i ++){ final View child = parent.getChildAt( i ) ; RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams(); final int top = child.getBottom() + layoutParams.bottomMargin ; final int bottom = top + mItemSize ; canvas.drawRect(left,top,right,bottom,mPaint); } } /** * 绘制横向 item 分割线 * @param canvas * @param parent */ private void drawHorizontal(Canvas canvas,RecyclerView parent){ final int top = parent.getPaddingTop() ; final int bottom = parent.getMeasuredHeight() - parent.getPaddingBottom() ; final int childSize = parent.getChildCount() ; for(int i = 0 ; i < childSize ; i ++){ final View child = parent.getChildAt( i ) ; RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams(); final int left = child.getRight() + layoutParams.rightMargin ; final int right = left + mItemSize ; canvas.drawRect(left,top,right,bottom,mPaint); } } /** * 设置item分割线的size * @param outRect * @param view * @param parent * @param state */ @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { if(mOrientation == LinearLayoutManager.VERTICAL){ outRect.set(0,0,0,mItemSize); }else { outRect.set(0,0,mItemSize,0); } } }
评论 (0)