您好,登錄后才能下訂單哦!
RecyclerView一個可以代替ListView和GridView的控件,那么RecyclerView到底比他們好在哪里?
RecyclerView架構提供了一種插拔式的體驗,所以實現了代碼的高度解耦,使用起來也異常的靈活。
我們可以通過設置它的LayoutManager控制其顯示的方式,通過ItemDecoration控制Item間的間隔,通過ItemAnimator控制Item的增刪動畫
RecyclerView.LayoutManager提供了三個實現類其中LinearLayoutManager 現行管理器,支持橫向、縱向,GridLayoutManager 網格布局管理器,StaggeredGridLayoutManager 瀑布就式布局管理器
那么先從LinearLayoutManager看起
先在gradle中引用compile 'com.android.support:recyclerview-v7:23.4.0'
Activity布局文件如下:
<?xml version="1.0" encoding="utf-8"?> <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="com.lg.recyclerviewdemo.LinearActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/linear_recycler" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout>
item布局文件:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <ImageView android:layout_width="70dp" android:layout_height="70dp" android:src="@drawable/android" /> <TextView android:id="@+id/recycler_item_tv" android:layout_width="wrap_content" android:layout_height="100dp" android:layout_marginLeft="20dp" android:gravity="center" android:textColor="@color/colorPrimary" android:textSize="20sp" android:textStyle="bold" /> </LinearLayout> </RelativeLayout>
在Acitvity中初始化數據:
mDatas = new ArrayList<String>(); for (int i = 1; i <= 65; i++) { mDatas.add("item"+i); }
核心代碼:
recyclerAdapter = new RecyclerAdapter(); //設置布局管理器 linear_recycler.setLayoutManager(new LinearLayoutManager(this)); //設置adapter linear_recycler.setAdapter(recyclerAdapter); //添加分割線 linear_recycler.addItemDecoration(new DividerLinearItemDecoration(this, DividerLinearItemDecoration.VERTICAL_LIST));
接下來自制adapter:
public class RecyclerAdapter extends RecyclerView.Adapter<LinearHolder> { private View view; @Override public LinearHolder onCreateViewHolder(ViewGroup parent, int viewType) { //利用反射將item的布局加載出來 view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, null); //new一個我們的ViewHolder,findViewById操作都在LinearHolder的構造方法中進行了 return new LinearHolder(view); } @Override public void onBindViewHolder(LinearHolder holder, int position) { holder.recycler_item.setText(MainActivity.mDatas.get(position)); } @Override public int getItemCount() { return MainActivity.mDatas.size(); } } class LinearHolder extends RecyclerView.ViewHolder { TextView recycler_item; public LinearHolder(View itemView) { super(itemView); recycler_item = (TextView) itemView.findViewById(R.id.recycler_item_tv); }
再繪畫它的分割線:
public class DividerLinearItemDecoration 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 DividerLinearItemDecoration(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) { 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); } } }
好了,我們來看看效果:
嘛,貌似和ListView沒什么區別,還這么麻煩
別急,我們試試GridLayoutManager
很簡單,我們只需要改變LayoutManager和ItemDecoration就行了:
grid_recycler.setLayoutManager(new GridLayoutManager(this,2)); grid_recycler.addItemDecoration(new DividerGridItemDecoration(this));
DividerGridItemDecoration代碼:
public class DividerGridItemDecoration extends RecyclerView.ItemDecoration { private static final int[] ATTRS = new int[] { android.R.attr.listDivider }; private Drawable mDivider; public DividerGridItemDecoration(Context context) { final TypedArray a = context.obtainStyledAttributes(ATTRS); mDivider = a.getDrawable(0); a.recycle(); } @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { drawHorizontal(c, parent); drawVertical(c, parent); } private int getSpanCount(RecyclerView parent) { // 列數 int spanCount = -1; RecyclerView.LayoutManager layoutManager = parent.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { spanCount = ((GridLayoutManager) layoutManager).getSpanCount(); } else if (layoutManager instanceof StaggeredGridLayoutManager) { spanCount = ((StaggeredGridLayoutManager) layoutManager) .getSpanCount(); } return spanCount; } public void drawHorizontal(Canvas c, RecyclerView parent) { 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.getLeft() - params.leftMargin; final int right = child.getRight() + params.rightMargin + mDivider.getIntrinsicWidth(); final int top = child.getBottom() + params.bottomMargin; final int bottom = top + mDivider.getIntrinsicHeight(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } public void drawVertical(Canvas c, RecyclerView parent) { 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 top = child.getTop() - params.topMargin; final int bottom = child.getBottom() + params.bottomMargin; final int left = child.getRight() + params.rightMargin; final int right = left + mDivider.getIntrinsicWidth(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } private boolean isLastColum(RecyclerView parent, int pos, int spanCount, int childCount) { RecyclerView.LayoutManager layoutManager = parent.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { if ((pos + 1) % spanCount == 0)// 如果是最后一列,則不需要繪制右邊 { return true; } } else if (layoutManager instanceof StaggeredGridLayoutManager) { int orientation = ((StaggeredGridLayoutManager) layoutManager) .getOrientation(); if (orientation == StaggeredGridLayoutManager.VERTICAL) { if ((pos + 1) % spanCount == 0)// 如果是最后一列,則不需要繪制右邊 { return true; } } else { childCount = childCount - childCount % spanCount; if (pos >= childCount)// 如果是最后一列,則不需要繪制右邊 return true; } } return false; } private boolean isLastRaw(RecyclerView parent, int pos, int spanCount, int childCount) { RecyclerView.LayoutManager layoutManager = parent.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { childCount = childCount - childCount % spanCount; if (pos >= childCount)// 如果是最后一行,則不需要繪制底部 return true; } else if (layoutManager instanceof StaggeredGridLayoutManager) { int orientation = ((StaggeredGridLayoutManager) layoutManager) .getOrientation(); // StaggeredGridLayoutManager 且縱向滾動 if (orientation == StaggeredGridLayoutManager.VERTICAL) { childCount = childCount - childCount % spanCount; // 如果是最后一行,則不需要繪制底部 if (pos >= childCount) return true; } else // StaggeredGridLayoutManager 且橫向滾動 { // 如果是最后一行,則不需要繪制底部 if ((pos + 1) % spanCount == 0) { return true; } } } return false; } @Override public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) { int spanCount = getSpanCount(parent); int childCount = parent.getAdapter().getItemCount(); if (isLastRaw(parent, itemPosition, spanCount, childCount))// 如果是最后一行,則不需要繪制底部 { outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0); } else if (isLastColum(parent, itemPosition, spanCount, childCount))// 如果是最后一列,則不需要繪制右邊 { outRect.set(0, 0, 0, mDivider.getIntrinsicHeight()); } else { outRect.set(0, 0, mDivider.getIntrinsicWidth(), mDivider.getIntrinsicHeight()); } } }
看下效果吧:
漬,有點意思,不過也沒那么神乎其神啊
別忘了,我們還有個StaggeredGridLayoutManager沒用
展示了那么多縱向的,我們來個橫向的,同樣改變LayoutManager
stag_grid_recycler.setLayoutManager(new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.HORIZONTAL));
看下效果:
一個RecyclerView就能實現這么多功能,確實強大啊
不過,你以為這樣就完了?下來要放大招了
看標題,瀑布流有木有,你用ListView不會那么簡單就實現吧,但是用RecyclerView分分鐘
稍微改變item布局,讓圖片放在字的上面
我們在onBindViewHolder給item設置隨機高度:
LayoutParams layoutParams = holder.sg_item.getLayoutParams(); layoutParams.height = heights.get(position);
看下大招效果:
我就問你6不6,6的話還不快關注我(嘎嘎)
好吧,可能嚇到你了,什么?點擊事件?
好吧,很不幸告訴你,要自己寫,對,就是要自己寫。
前面已經說過了,RecyclerView實現了高度解耦,非常的靈活(你要干什么,自己去寫)。那就寫吧!
先寫個接口:
public interface OnItemClickLitener { /*點擊事件*/ void onItemClick(View view, int position); /*長按事件*/ void onItemLongClick(View view, int position); }
在adapter中加入代碼:
private OnItemClickLitener mOnItemClickLitener; public void setOnItemClickLitener(OnItemClickLitener mOnItemClickLitener) { this.mOnItemClickLitener = mOnItemClickLitener; }
onBindViewHolder方法中加入:
holder.sg_item.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int pos = holder.getLayoutPosition(); mOnItemClickLitener.onItemClick(holder.itemView, pos); } }); holder.sg_item.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { int pos = holder.getLayoutPosition(); mOnItemClickLitener.onItemLongClick(holder.itemView, pos); return false; } });
然后在Activity中調用:
staggeredGridAdapter.setOnItemClickLitener(new OnItemClickLitener() { @Override public void onItemClick(View view, int position) { staggeredGridAdapter.notifyItemRemoved(position); } @Override public void onItemLongClick(View view, final int position) { android.support.v7.app.AlertDialog.Builder builder = new AlertDialog.Builder(StaggeredGridVActivity.this); builder.setTitle("Delete?") .setNegativeButton("no", null) .setPositiveButton("yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { staggeredGridAdapter.notifyItemRemoved(position); Toast.makeText(StaggeredGridVActivity.this,MainActivity.mDatas.get(position),Toast.LENGTH_SHORT).show(); } }).show(); } });
效果圖:
怎么樣?厲害吧。不過你以為這樣就完了?
如果我想要將item托拉拽再加上側滑刪除呢?
首先,如果要實現托拉拽功能,那item長按事件還是不要寫代碼的,避免事件沖突
然后在Activity中加入代碼:
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback); itemTouchHelper.attachToRecyclerView(stag_v_recycler);
callback代碼:
ItemTouchHelper.Callback callback = new ItemTouchHelper.Callback() { //這個方法是用來設置我們拖動的方向以及側滑的方向的 @Override public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) { //設置拖拽方向為上下左右 final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT; //設置側滑方向為從左到右和從右到左都可以 final int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END; //將方向參數設置進去 return makeMovementFlags(dragFlags, swipeFlags); } /** * @param recyclerView * @param viewHolder 拖動的ViewHolder * @param target 目標位置的ViewHolder * @return */ @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { int fromPosition = viewHolder.getAdapterPosition();//得到拖動ViewHolder的position int toPosition = target.getAdapterPosition();//得到目標ViewHolder的position if (fromPosition < toPosition) { //分別把中間所有的item的位置重新交換 for (int i = fromPosition; i < toPosition; i++) { Collections.swap(MainActivity.mDatas, i, i + 1); } } else { for (int i = fromPosition; i > toPosition; i--) { Collections.swap(MainActivity.mDatas, i, i - 1); } } staggeredGridAdapter.notifyItemMoved(fromPosition, toPosition); //返回true表示執行拖動 return true; } @Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { int position = viewHolder.getAdapterPosition(); staggeredGridAdapter.notifyItemRemoved(position); } @Override public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive); if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) { //滑動時改變Item的透明度 final float alpha = 1 - Math.abs(dX) / (float) viewHolder.itemView.getWidth(); viewHolder.itemView.setAlpha(alpha); viewHolder.itemView.setTranslationX(dX); } } };
OK,我們來看看效果:
如果你喜歡我的文章,那就關注我的博客吧,我會不定期的發些技術貼
源碼地址:http://down.51cto.com/data/2222200
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。