当前位置:   article > 正文

RecyclerView简单使用总结_recyclerview 使用方法总结实验报告

recyclerview 使用方法总结实验报告

刚学习了RecyclerView,在这里对自己学习的内容进行一个总结,方便以后查看。

现在学习的知识很浅,只是知道如何去使用,而没有去研究它的源码,不知道它的内部具体原理是如何。

这篇文章大概有些说法是不对的,希望下次有机会用到RecyclerView来看这篇文章可以修改里面描述不对的语句。

希望看到这篇文章的人有不对之处可以帮助指出,谢谢。

正文开始。

导入RecyclerView的依赖包


实现类似ListView的功能

RecyclerView与ListView类似,需要适配器来填充数据。具体的步骤与非常熟悉的ListView一样。

首先activity的布局

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical" android:layout_width="match_parent"
  4. android:layout_height="match_parent">
  5. <android.support.v7.widget.RecyclerView
  6. android:id="@+id/recycler_view"
  7. android:layout_width="match_parent"
  8. android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>
  9. </LinearLayout>

item的布局

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical" android:layout_width="match_parent"
  4. android:layout_height="wrap_content">
  5. <TextView
  6. android:id="@+id/tv_text"
  7. android:layout_width="match_parent"
  8. android:layout_height="wrap_content"
  9. android:text="text"
  10. android:textColor="@color/textColor"
  11. android:padding="10dp"
  12. android:gravity="center"
  13. android:textSize="18sp"
  14. android:background="@color/textBackground"/>
  15. </LinearLayout>

很简单,item就是一个TextView。

适配器

  1. package example.com.rvdemo;
  2. import android.content.Context;
  3. import android.support.v7.widget.RecyclerView;
  4. import android.util.Log;
  5. import android.view.LayoutInflater;
  6. import android.view.View;
  7. import android.view.ViewGroup;
  8. import android.widget.TextView;
  9. import java.util.List;
  10. /**
  11. * Created by csjy on 2017/4/18.
  12. */
  13. public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder>{
  14. private List<String> mList;
  15. private LayoutInflater inflater;
  16. public RecyclerAdapter(Context context, List<String> mList){
  17. inflater = LayoutInflater.from(context);
  18. this.mList = mList;
  19. }
  20. @Override
  21. public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
  22. MyViewHolder holder = new MyViewHolder(inflater.inflate(R.layout.item_recycler_view,parent,false));
  23. return holder;
  24. }
  25. @Override
  26. public void onBindViewHolder(MyViewHolder holder, int position) {
  27. holder.tvText.setText(mList.get(position));
  28. }
  29. @Override
  30. public int getItemCount() {
  31. return mList.size();
  32. }
  33. class MyViewHolder extends RecyclerView.ViewHolder{
  34. private TextView tvText;
  35. public MyViewHolder(View itemView) {
  36. super(itemView);
  37. tvText = (TextView) itemView.findViewById(R.id.tv_text);
  38. }
  39. }
  40. }

它需要继承RecyclerView的Adapter<VH extends ViewHolder>,所以写一个自己的ViewHolder类继承自RecyclerView的ViewHolder。重写三个方法,方法的功能一看名字就了然。

Activity

  1. package example.com.rvdemo;
  2. import android.content.Context;
  3. import android.os.Bundle;
  4. import android.support.v7.app.AppCompatActivity;
  5. import android.support.v7.widget.LinearLayoutManager;
  6. import android.support.v7.widget.RecyclerView;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. /**
  10. * Created by csjy on 2017/4/18.
  11. */
  12. public class ListViewActivity extends AppCompatActivity {
  13. private RecyclerView mRecyclerView;
  14. private Context context;
  15. private RecyclerAdapter adapter;
  16. private List<String> mList;
  17. @Override
  18. public void onCreate(Bundle savedInstanceState) {
  19. super.onCreate(savedInstanceState);
  20. setContentView(R.layout.recycler_view);
  21. initDatas();
  22. initView();
  23. }
  24. private void initDatas() {
  25. mList = new ArrayList<String>();
  26. for (int i = 0; i < 100; i++){
  27. mList.add(""+ i);
  28. }
  29. }
  30. private void initView() {
  31. context = MyApplication.getContext();
  32. mRecyclerView = (RecyclerView) this.findViewById(R.id.recycler_view);
  33. mRecyclerView.setLayoutManager(new LinearLayoutManager(context));
  34. adapter = new RecyclerAdapter(context,mList);
  35. mRecyclerView.setAdapter(adapter);
  36. }
  37. }

initDatas()方法必须在initView()方法前,不然适配器中getItemCount()返回值为空,很简单的问题,确很容易犯。

效果图


可以看到无分割线。现在给item添加分割线

  1. package example.com.rvdemo;
  2. import android.content.Context;
  3. import android.content.res.TypedArray;
  4. import android.graphics.Canvas;
  5. import android.graphics.Rect;
  6. import android.graphics.drawable.Drawable;
  7. import android.support.v7.widget.RecyclerView;
  8. import android.view.View;
  9. import android.widget.LinearLayout;
  10. /**
  11. * Created by csjy on 2017/4/19.
  12. */
  13. public class RecyclerItemDecoration extends RecyclerView.ItemDecoration {
  14. private static final int[] ATTRS = new int[]{android.R.attr.listDivider};
  15. /**
  16. * 分割线
  17. */
  18. private Drawable mDivider;
  19. /**
  20. * 方向,水平/垂直
  21. */
  22. private int mOrientation;
  23. RecyclerItemDecoration(Context context,int orientation){
  24. TypedArray ta = context.obtainStyledAttributes(ATTRS);
  25. mDivider = ta.getDrawable(0);
  26. ta.recycle();
  27. this.mOrientation = orientation;
  28. }
  29. @Override
  30. public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
  31. super.onDraw(c, parent, state);
  32. if(mOrientation == LinearLayout.HORIZONTAL){
  33. drawHorizontal(c,parent);
  34. }else if(mOrientation == LinearLayout.VERTICAL){
  35. drawVertical(c,parent);
  36. }
  37. }
  38. private void drawVertical(Canvas c, RecyclerView parent) {
  39. int left = parent.getLeft();
  40. int right = parent.getRight();
  41. int childCount = parent.getChildCount();
  42. for (int i = 0; i < childCount; i++){
  43. View child = parent.getChildAt(i);
  44. RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
  45. int top = child.getBottom() + params.bottomMargin;
  46. int buttom = top + mDivider.getIntrinsicHeight();
  47. mDivider.setBounds(left,top,right,buttom);
  48. mDivider.draw(c);
  49. }
  50. }
  51. private void drawHorizontal(Canvas c, RecyclerView parent) {
  52. int top = parent.getTop();
  53. int bottom = parent.getBottom();
  54. int childCount = parent.getChildCount();
  55. for(int i = 0; i < childCount; i++){
  56. View child = parent.getChildAt(i);
  57. RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
  58. int left = child.getLeft() + params.leftMargin;
  59. int right = left + mDivider.getIntrinsicWidth();
  60. mDivider.setBounds(left,top,right,bottom);
  61. mDivider.draw(c);
  62. }
  63. }
  64. @Override
  65. public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
  66. super.getItemOffsets(outRect, view, parent, state);
  67. if(mOrientation == LinearLayout.VERTICAL){
  68. outRect.set(0,0,0,mDivider.getIntrinsicHeight());
  69. }else if(mOrientation == LinearLayout.HORIZONTAL){
  70. outRect.set(0,0,mDivider.getIntrinsicWidth(),0);
  71. }
  72. }
  73. }

首先在onDraw()方法里做一个判断,它的方向是垂直还是水平

drawVertical()与drawHorizontal()方法见图


看到图就知道里面的left、top、right、bottom是怎么算的。

最后调用getItemOffset()方法,画出分割线。

效果图


在这里说几个RecyclerView常用的方法。

  1. setLayoutManager()   RecyclerView显示的方式,主要用到有LinearLayoutManager,GridLayoautManager,StaggeredGridLayoutManager(必须)
  2. addItemDecoration()  添加分割线(不是必须)
  3. setAnimation()  item增删动画(不是必须)
  4. setAdapter()  适配器,不用说(必须)

实现类似GridView的功能

只需要修改分割线的代码,GridView垂直水平两个方向都有。

  1. package example.com.rvdemo;
  2. import android.content.Context;
  3. import android.content.res.TypedArray;
  4. import android.graphics.Canvas;
  5. import android.graphics.Paint;
  6. import android.graphics.Rect;
  7. import android.graphics.drawable.Drawable;
  8. import android.support.v7.widget.GridLayoutManager;
  9. import android.support.v7.widget.RecyclerView;
  10. import android.support.v7.widget.StaggeredGridLayoutManager;
  11. import android.util.Log;
  12. import android.view.View;
  13. import android.widget.LinearLayout;
  14. /**
  15. * Created by csjy on 2017/4/19.
  16. */
  17. public class RecyclerGridItemDecoration extends RecyclerView.ItemDecoration {
  18. // private static final int [] ATTRS = new int[]{android.R.attr.listDivider};
  19. private Drawable mDividerV,mDividerH;
  20. // RecyclerGridItemDecoration(Context context){
  21. //
  22. // TypedArray ta = context.obtainStyledAttributes(ATTRS);
  23. // mDividerV = ta.getDrawable(0);
  24. // ta.recycle();
  25. // }
  26. RecyclerGridItemDecoration(Context context,int drawableVertical,int drawableHorizontal){
  27. mDividerV = context.getResources().getDrawable(drawableVertical);
  28. mDividerH = context.getResources().getDrawable(drawableHorizontal);
  29. }
  30. @Override
  31. public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
  32. super.onDraw(c, parent, state);
  33. drawVertical(c,parent);
  34. drawHorizontal(c,parent);
  35. }
  36. private void drawHorizontal(Canvas c, RecyclerView parent) {
  37. int childCount = parent.getChildCount();
  38. for (int i = 0; i < childCount; i++){
  39. View child = parent.getChildAt(i);
  40. LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) parent.getLayoutParams();
  41. final int left = child.getLeft() + params.leftMargin;
  42. final int right = child.getRight() + params.rightMargin
  43. + mDividerH.getIntrinsicWidth();
  44. final int top = child.getBottom() + params.bottomMargin;
  45. final int bottom = top + mDividerH.getIntrinsicHeight();
  46. mDividerH.setBounds(left, top, right, bottom);
  47. mDividerH.draw(c);
  48. }
  49. }
  50. private void drawVertical(Canvas c, RecyclerView parent) {
  51. int childCount = parent.getChildCount();
  52. for (int i = 0; i < childCount; i++){
  53. View child = parent.getChildAt(i);
  54. LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) parent.getLayoutParams();
  55. final int top = child.getTop() - params.topMargin;
  56. final int bottom = child.getBottom() + params.bottomMargin;
  57. final int left = child.getRight() + params.rightMargin;
  58. final int right = left + mDividerV.getIntrinsicWidth();
  59. mDividerV.draw(c);
  60. mDividerV.setBounds(left,top,right,bottom);
  61. }
  62. }
  63. /**
  64. * 获取行/列数
  65. * @param parent
  66. * @return
  67. */
  68. private int getSpanCount(RecyclerView parent){
  69. int spanCount = 0;
  70. RecyclerView.LayoutManager manager = parent.getLayoutManager();
  71. if(manager instanceof GridLayoutManager){
  72. spanCount = ((GridLayoutManager) manager).getSpanCount();
  73. }else if(manager instanceof StaggeredGridLayoutManager){
  74. spanCount = ((StaggeredGridLayoutManager) manager).getSpanCount();
  75. }
  76. return spanCount;
  77. }
  78. /**
  79. * 判断是否是最后一列
  80. * 如果是最后一列就不画最右边的分割线
  81. * true:是最后一列
  82. * false: 不是最后一列
  83. * @param parent
  84. * @param position item的位置
  85. * @param childCount item的总数
  86. * @param spanCount 行/列数
  87. * @return
  88. */
  89. private boolean isLastColum(RecyclerView parent, int position, int childCount, int spanCount){
  90. RecyclerView.LayoutManager manager = parent.getLayoutManager();
  91. if(manager instanceof GridLayoutManager){
  92. if((position + 1) % spanCount == 0){
  93. return true;
  94. }
  95. }else if(manager instanceof StaggeredGridLayoutManager){
  96. int orientation = ((StaggeredGridLayoutManager) manager).getOrientation();
  97. if(orientation == StaggeredGridLayoutManager.VERTICAL){
  98. if((position + 1) % spanCount == 0){
  99. return true;
  100. }
  101. }else if(orientation == StaggeredGridLayoutManager.HORIZONTAL){
  102. childCount = (childCount % spanCount == 0)?(childCount - spanCount):(childCount - childCount % spanCount);
  103. if (position >= childCount){
  104. return true;
  105. }
  106. }
  107. }
  108. return false;
  109. }
  110. /**
  111. * 判断是否是最后一行
  112. * 如果是最后一行,就不画最下边的分割线
  113. * true :是最后一行
  114. * false: 不是最后一行
  115. * @param parent
  116. * @param position 当前的位置
  117. * @param childCount item的总数
  118. * @param spanCount 行/列数
  119. * @return
  120. */
  121. private boolean isLastRow(RecyclerView parent, int position, int childCount, int spanCount){
  122. RecyclerView.LayoutManager manager = parent.getLayoutManager();
  123. if(manager instanceof GridLayoutManager){
  124. childCount = (childCount % spanCount == 0)?(childCount - spanCount):(childCount - childCount % spanCount);
  125. if (position >= childCount){
  126. return true;
  127. }
  128. }else if(manager instanceof StaggeredGridLayoutManager){
  129. int orientation = ((StaggeredGridLayoutManager) manager).getOrientation();
  130. if(orientation == StaggeredGridLayoutManager.VERTICAL){
  131. childCount = (childCount % spanCount == 0)?(childCount - spanCount):(childCount - childCount % spanCount);
  132. if (position >= childCount){
  133. return true;
  134. }
  135. }else if(orientation == StaggeredGridLayoutManager.HORIZONTAL){
  136. if((position + 1) % spanCount == 0){
  137. return true;
  138. }
  139. }
  140. }
  141. return false;
  142. }
  143. @Override
  144. public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
  145. super.getItemOffsets(outRect, itemPosition, parent);
  146. Log.d("Tag","itemPosition====" + itemPosition);
  147. int spanCount = getSpanCount(parent);
  148. int childCount = parent.getAdapter().getItemCount();
  149. outRect.set(0, 0, isLastColum(parent,itemPosition,childCount,spanCount) ? 0 : mDividerV.getIntrinsicWidth(),
  150. isLastRow(parent,itemPosition,childCount,spanCount) ? 0 : mDividerH.getIntrinsicHeight());
  151. }
  152. }

Activity的代码:

  1. package example.com.rvdemo;
  2. import android.content.Context;
  3. import android.os.Bundle;
  4. import android.support.v7.app.AppCompatActivity;
  5. import android.support.v7.widget.GridLayoutManager;
  6. import android.support.v7.widget.RecyclerView;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. /**
  10. * Created by csjy on 2017/4/18.
  11. */
  12. public class GridViewActivity extends AppCompatActivity {
  13. private RecyclerView mRecyclerView;
  14. private Context context;
  15. private RecyclerAdapter adapter;
  16. private List<String> mList;
  17. @Override
  18. public void onCreate(Bundle savedInstanceState) {
  19. super.onCreate(savedInstanceState);
  20. setContentView(R.layout.recycler_view);
  21. initDatas();
  22. initView();
  23. }
  24. private void initDatas() {
  25. mList = new ArrayList<String>();
  26. for (int i = 0; i < 100; i++){
  27. mList.add(""+ i);
  28. }
  29. }
  30. private void initView() {
  31. context = MyApplication.getContext();
  32. mRecyclerView = (RecyclerView) this.findViewById(R.id.recycler_view);
  33. mRecyclerView.setLayoutManager(new GridLayoutManager(context,4));
  34. adapter = new RecyclerAdapter(context,mList);
  35. mRecyclerView.setAdapter(adapter);
  36. RecyclerGridItemDecoration decoration = new RecyclerGridItemDecoration(context,R.drawable.divider_vertical,R.drawable.divider);
  37. mRecyclerView.addItemDecoration(decoration);
  38. }
  39. }

两个drawable:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:shape="rectangle" >
  4. <solid android:color="#0011ff"/>
  5. <size android:height="4dp"/>
  6. </shape>

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:shape="rectangle" >
  4. <solid android:color="#FFFF0004"/>
  5. <size android:width="4dp"/>
  6. </shape>


首先画水平,垂直的分割线。看图


看图一目了然,接下来getSpanCount()方法,用来获取行数或者列数,首先实例化LayoutManager,判断LayoutManager的实例为GridLayoutManager还是StaggeredGridLayoutManager,调用相应LayoutManager的getSpanCount()获取行/列数。

isLastColumn()与isLastRow()方法判断是否为最后一列,最后一行。

首先先解释GridLayoutManger,如果是垂直的情况,见下图


判断是否为最后一列:

这里假设有3列,spanCount = 3; 用position + 1 与spanCount求余,第一行:3%3 =0;第二行:6%3=0,所以,如果为零,说明为最后一列,返回true。

判断是否为最后一行:

假设item的总数为100,childCount = 100; 用childCount与spanCount求余,childCount % spanCount == 0,就是标准的column*row;childCount % spanCount == 1:见上图,以此类推。

进行一个判断,如果childCount % spanCount == 0,就是标准的column*row,将childCount - spanCount 赋值给childCount,至于为什么要这样赋值,是因为

childCount - spanCount 就相当于把最后一行减去,一旦当前item的位置大于倒数第二行,就说明是最后一行(这说的有点抽象。。但是挺好理解的)。如果

childCount % spanCount  != 0,用childCount - childCount % spanCount也是把最后一行减去,那么一旦当前item的位置大于倒数第二行,就说明是最后一行。

最后调用getItemOffet()方法做一个小偏移。

水平的情况:


判断最后一列的情况就与垂直情况下的判断最后一行的情况一样,见代码

判断最后一行的情况就与垂直情况下的判断最后一列的情况一样。

StaggeredGridLayoutManager的判断方式与GridLayoutManager的方式一样,看到代码就可以理解。

效果图:




实现类似瀑布流的功能

只需要简单修改适配器的代码,给item加上随机的高度就可以,修改几句代码,改为:

  1. mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(6,StaggeredGridLayoutManager.VERTICAL));
  2. adapter = new StaggeredAdapter(context,mList);
  3. mRecyclerView.setAdapter(adapter);


修改后的适配器代码:

  1. package example.com.rvdemo;
  2. import android.content.Context;
  3. import android.support.v7.widget.RecyclerView;
  4. import android.util.Log;
  5. import android.view.LayoutInflater;
  6. import android.view.View;
  7. import android.view.ViewGroup;
  8. import android.widget.LinearLayout;
  9. import android.widget.TextView;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. /**
  13. * Created by csjy on 2017/4/19.
  14. */
  15. public class StaggeredAdapter extends RecyclerView.Adapter<StaggeredAdapter.MyViewHolder>{
  16. private List<String> mList;
  17. private List<Integer> mHeight;
  18. private LayoutInflater inflater;
  19. StaggeredAdapter(Context context,List<String> mList){
  20. inflater = LayoutInflater.from(context);
  21. this.mList = mList;
  22. mHeight = new ArrayList<Integer>();
  23. for(int i = 0; i < mList.size(); i++){
  24. mHeight.add((int)(200 + Math.random() * 500));
  25. Log.d("Tag", String.valueOf((100 + Math.random() * 300)));
  26. }
  27. }
  28. @Override
  29. public StaggeredAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
  30. MyViewHolder holder = new MyViewHolder(inflater.inflate(R.layout.item_recycler_view,parent,false));
  31. return holder;
  32. }
  33. @Override
  34. public void onBindViewHolder(StaggeredAdapter.MyViewHolder holder, int position) {
  35. LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) holder.tvText.getLayoutParams();
  36. params.height = mHeight.get(position);
  37. holder.tvText.setLayoutParams(params);
  38. holder.tvText.setText(mList.get(position));
  39. }
  40. @Override
  41. public int getItemCount() {
  42. return mList.size();
  43. }
  44. class MyViewHolder extends RecyclerView.ViewHolder{
  45. private TextView tvText;
  46. public MyViewHolder(View itemView) {
  47. super(itemView);
  48. tvText = (TextView) itemView.findViewById(R.id.tv_text);
  49. }
  50. }
  51. }

只是新增了一个给item设置随机的高。

效果图:



实现类似Gallery的功能

先看效果图


思路如下:自定义一个RecyclerView,定义一个接口,当RecyclerView发生滚动时回调。

自定义RecyclerView:

  1. package example.com.rvdemo;
  2. import android.content.Context;
  3. import android.support.v7.widget.RecyclerView;
  4. import android.util.AttributeSet;
  5. import android.view.View;
  6. /**
  7. * Created by csjy on 2017/4/20.
  8. */
  9. public class MyRecyclerView extends RecyclerView {
  10. private View currentView;
  11. public MyRecyclerView(Context context,AttributeSet attrs) {
  12. super(context, attrs);
  13. }
  14. @Override
  15. protected void onLayout(boolean changed, int l, int t, int r, int b) {
  16. super.onLayout(changed, l, t, r, b);
  17. if (onItemScrollListener != null) {
  18. currentView = getChildAt(0);
  19. onItemScrollListener.OnChange(currentView,getChildAdapterPosition(currentView));
  20. }
  21. }
  22. public interface OnItemScrollListener{
  23. void OnChange(View view,int position);
  24. }
  25. private OnItemScrollListener onItemScrollListener;
  26. public void setOnItemScrollListener(OnItemScrollListener onItemScrollListener) {
  27. this.onItemScrollListener = onItemScrollListener;
  28. }
  29. @Override
  30. public void onScrolled(int dx, int dy) {
  31. super.onScrolled(dx, dy);
  32. View newView;
  33. newView = getChildAt(0);
  34. if(onItemScrollListener != null){
  35. if (newView != null && newView != currentView){
  36. currentView = newView;
  37. onItemScrollListener.OnChange(currentView,getChildAdapterPosition(currentView));
  38. }
  39. }
  40. }
  41. }

adapter:

  1. package example.com.rvdemo;
  2. import android.content.Context;
  3. import android.support.v7.widget.RecyclerView;
  4. import android.view.LayoutInflater;
  5. import android.view.View;
  6. import android.view.ViewGroup;
  7. import android.widget.ImageView;
  8. import java.util.List;
  9. /**
  10. * Created by csjy on 2017/4/19.
  11. */
  12. public class GalleryAdapter extends RecyclerView.Adapter<GalleryAdapter.MyViewHolder>{
  13. private List<Integer> mList;
  14. private LayoutInflater inflater;
  15. GalleryAdapter(Context context, List<Integer> mList) {
  16. inflater = LayoutInflater.from(context);
  17. this.mList = mList;
  18. }
  19. @Override
  20. public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
  21. MyViewHolder holder = new MyViewHolder(inflater.inflate(R.layout.item_recycler_gallery,parent,false));
  22. return holder;
  23. }
  24. @Override
  25. public void onBindViewHolder(MyViewHolder holder, final int position) {
  26. holder.ivImage.setBackgroundResource(mList.get(position));
  27. if (onItemClickListener != null){
  28. holder.ivImage.setOnClickListener(new View.OnClickListener() {
  29. @Override
  30. public void onClick(View v) {
  31. onItemClickListener.onItemClick(position);
  32. }
  33. });
  34. }
  35. }
  36. @Override
  37. public int getItemCount() {
  38. return mList.size();
  39. }
  40. class MyViewHolder extends RecyclerView.ViewHolder{
  41. private ImageView ivImage;
  42. public MyViewHolder(View itemView) {
  43. super(itemView);
  44. ivImage = (ImageView) itemView.findViewById(R.id.iv_image);
  45. }
  46. }
  47. public interface OnItemClickListener{
  48. void onItemClick(int position);
  49. }
  50. private OnItemClickListener onItemClickListener;
  51. public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
  52. this.onItemClickListener = onItemClickListener;
  53. }
  54. }

adapter中自定义了一个接口,当有点击事件时回调。

Activity:

  1. package example.com.rvdemo;
  2. import android.content.Context;
  3. import android.content.Intent;
  4. import android.os.Bundle;
  5. import android.support.v7.app.AppCompatActivity;
  6. import android.support.v7.widget.LinearLayoutManager;
  7. import android.support.v7.widget.RecyclerView;
  8. import android.view.View;
  9. import android.widget.ImageView;
  10. import android.widget.Toast;
  11. import java.util.ArrayList;
  12. import java.util.Arrays;
  13. import java.util.List;
  14. /**
  15. * Created by csjy on 2017/4/19.
  16. */
  17. public class GalleryActivity extends AppCompatActivity{
  18. private MyRecyclerView mRecyclerView;
  19. private Context context;
  20. private GalleryAdapter adapter;
  21. private List<Integer> mList;
  22. private ImageView ivBig;
  23. @Override
  24. public void onCreate(Bundle savedInstanceState) {
  25. super.onCreate(savedInstanceState);
  26. setContentView(R.layout.recycler_gallery);
  27. initDatas();
  28. initView();
  29. initEvent();
  30. }
  31. private void initEvent() {
  32. adapter.setOnItemClickListener(new GalleryAdapter.OnItemClickListener() {
  33. @Override
  34. public void onItemClick(int position) {
  35. // Toast.makeText(context, "you click" + position, Toast.LENGTH_SHORT).show();
  36. ivBig.setBackgroundResource(mList.get(position));
  37. }
  38. });
  39. mRecyclerView.setOnItemScrollListener(new MyRecyclerView.OnItemScrollListener() {
  40. @Override
  41. public void OnChange(View view, int position) {
  42. ivBig.setBackgroundResource(mList.get(position));
  43. }
  44. });
  45. }
  46. private void initDatas() {
  47. mList = new ArrayList<Integer>(Arrays.asList(R.mipmap.a,R.mipmap.b,R.mipmap.c,R.mipmap.d,R.mipmap.e,
  48. R.mipmap.f,R.mipmap.g,R.mipmap.h,R.mipmap.i,R.mipmap.j,R.mipmap.k,R.mipmap.l,R.mipmap.m));
  49. }
  50. private void initView() {
  51. context = MyApplication.getContext();
  52. mRecyclerView = (MyRecyclerView) this.findViewById(R.id.gallery_recycler);
  53. LinearLayoutManager manager = new LinearLayoutManager(context);
  54. manager.setOrientation(LinearLayoutManager.HORIZONTAL);
  55. mRecyclerView.setLayoutManager(manager);
  56. adapter = new GalleryAdapter(context,mList);
  57. mRecyclerView.setAdapter(adapter);
  58. ivBig = (ImageView)this.findViewById(R.id.iv_big_image);
  59. }
  60. }

activity很简单,一看就明白,这里不做记录。

参考自:【张鸿洋的博客】http://blog.csdn.net/lmj623565791/article/details/38173061 

完毕。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/529854
推荐阅读
相关标签
  

闽ICP备14008679号