Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> RecyclerView,androidrecyclerview

RecyclerView,androidrecyclerview

編輯:關於android開發

RecyclerView,androidrecyclerview


1.簡介

  RecyclerView是一種新的視圖組,目標是為任何基於適配器的視圖提供相似的渲染方式。它被作為ListView和GridView控件的繼承者,在最新的support-V7版本中提供支持。RecyclerView架構,提供了一種插拔式的體驗,高度的解耦,異常的靈活,通過設置它提供的不同LayoutManager,ItemDecoration , ItemAnimator實現令人瞠目的效果。

總之ListView和GridView能做的RecyclerView都能做,並且能實現瀑布流效果

2.使用

在build.gradle配置RecyclerView的庫
compile 'com.android.support:recyclerview-v7:23.3.0'

 

//設置RecyclerView的適配器
adapter = new MyRecyclerViewAdapter(RecyclerViewActivity.this,datas);
recyclerview.setAdapter(adapter);

//LayoutManager
recyclerview.setLayoutManager(new LinearLayoutManager(RecyclerViewActivity.this, LinearLayoutManager.VERTICAL, false));
//        recyclerview.scrollToPosition(datas.size()-1);

//添加RecyclerView的分割線
recyclerview.addItemDecoration(new DividerListItemDecoration(RecyclerViewActivity.this,DividerListItemDecoration.VERTICAL_LIST));

//設置動畫
recyclerview.setItemAnimator(new DefaultItemAnimator());

  

public class MyAdapter extends  RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    private final Context context;
    private final ArrayList<String> datas;
   
    public MyAdapter(Context context,ArrayList<String> datas){
        this.context = context;
        this.datas = datas;
    }
    /**
     * 相當於ListView適配器中的getView的創建holder布局
     *
     * @param parent
     * @param viewType
     * @return
     */
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = View.inflate(context, R.layout.item_hello, null);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.tv_text.setText(datas.get(position));
        holder.iv_icon.setBackgroundResource(R.mipmap.ic_launcher);

    }

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

    class MyViewHolder extends RecyclerView.ViewHolder {

        private TextView tv_text;
        private ImageView iv_icon;

        public MyViewHolder(View itemView) {
            super(itemView);
            tv_text = (TextView) itemView.findViewById(R.id.tv_text);
            iv_icon = (ImageView) itemView.findViewById(R.id.iv_icon);

        }
    }
}

  

3.設置ListView&GridView&瀑布流類型效果

//設置List類型效果
recyclerview.setLayoutManager(new LinearLayoutManager(RecyclerViewActivity.this,LinearLayoutManager.VERTICAL,false));

//設置Grid類型效果
recyclerview.setLayoutManager(new GridLayoutManager(RecyclerViewActivity.this, 2, GridLayoutManager.VERTICAL, false));
//recyclerview.scrollToPosition(99);

//設置瀑布流類型效果
recyclerview.setLayoutManager(new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL));

  

4.分割線

參照網址:http://blog.csdn.net/lmj623565791/article/details/45059587

//設置分割線-分割線需要自定義&還可以自定義分割線的樣式
//沒有提供默認的分割線
recyclerview.addItemDecoration(new DividerListItemDecoration(this, DividerListItemDecoration.VERTICAL_LIST));

  

 1 public class DividerListItemDecoration extends RecyclerView.ItemDecoration {
 2     private static final int[] ATTRS = new int[]{
 3             android.R.attr.listDivider
 4     };
 5 
 6     public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
 7 
 8     public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;
 9 
10     private Drawable mDivider;
11 
12     private int mOrientation;
13 
14     public DividerListItemDecoration(Context context, int orientation) {
15         final TypedArray a = context.obtainStyledAttributes(ATTRS);
16         mDivider = a.getDrawable(0);
17         a.recycle();
18         setOrientation(orientation);
19     }
20 
21     public void setOrientation(int orientation) {
22         if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
23             throw new IllegalArgumentException("invalid orientation");
24         }
25         mOrientation = orientation;
26     }
27 
28     @Override
29     public void onDraw(Canvas c, RecyclerView parent) {
30 //        Log.e("recyclerview - itemdecoration", "onDraw()");
31 
32         if (mOrientation == VERTICAL_LIST) {
33             drawVertical(c, parent);
34         } else {
35             drawHorizontal(c, parent);
36         }
37 
38     }
39 
40 
41     public void drawVertical(Canvas c, RecyclerView parent) {
42         final int left = parent.getPaddingLeft();
43         final int right = parent.getWidth() - parent.getPaddingRight();
44 
45         final int childCount = parent.getChildCount();
46         for (int i = 0; i < childCount; i++) {
47             final View child = parent.getChildAt(i);
48             android.support.v7.widget.RecyclerView v = new android.support.v7.widget.RecyclerView(parent.getContext());
49             final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
50                     .getLayoutParams();
51             final int top = child.getBottom() + params.bottomMargin;
52             final int bottom = top + mDivider.getIntrinsicHeight();
53             mDivider.setBounds(left, top, right, bottom);
54             mDivider.draw(c);
55         }
56     }
57 
58     public void drawHorizontal(Canvas c, RecyclerView parent) {
59         final int top = parent.getPaddingTop();
60         final int bottom = parent.getHeight() - parent.getPaddingBottom();
61 
62         final int childCount = parent.getChildCount();
63         for (int i = 0; i < childCount; i++) {
64             final View child = parent.getChildAt(i);
65             final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
66                     .getLayoutParams();
67             final int left = child.getRight() + params.rightMargin;
68             final int right = left + mDivider.getIntrinsicHeight();
69             mDivider.setBounds(left, top, right, bottom);
70             mDivider.draw(c);
71         }
72     }
73 
74     @Override
75     public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
76         if (mOrientation == VERTICAL_LIST) {
77             outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
78         } else {
79             outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
80         }
81     }
82 }
DividerListItemDecoration

 

設置分割線樣式:

①application設置

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:listDivider">@drawable/divider_bg</item>
</style>

②在activity中

<activity android:name=".recyclerview.RecyclerViewActivity"
    android:theme="@style/listDividerTheme"/>
<style name="listDividerTheme"  parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:listDivider">@drawable/divider_bg</item>
</style>

  

5.自定義設置item的點擊事件

RecyclerView默認是沒有點擊事件的,需要自定義點擊事件
用到知識點:接口,getLayoutPosition()

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{

    private final Context context;
    private final ArrayList<String> datas;

    //設置點擊某個item的監聽
    public interface OnItemClickListener{
         void onItemClick(View view,int position,String content);
    }

    private OnItemClickListener onItemClickListener;
    public void setOnItemClickListener(OnItemClickListener onItemClickListener)   {
        this.onItemClickListener = onItemClickListener;
    }

    //設置點擊圖片
    public interface OnImageViewClickListener{
        void onImageViewClick(View view,int position);
    }

    private OnImageViewClickListener onImageViewClickListener;
    public void setOnImageViewClickListener(OnImageViewClickListener onImageViewClickListener) {
        this.onImageViewClickListener = onImageViewClickListener;
    }

  ...................................

    class MyViewHolder extends RecyclerView.ViewHolder {

        private TextView tv_text;
        private ImageView iv_icon;

        public MyViewHolder(View itemView) {
            super(itemView);
            tv_text = (TextView) itemView.findViewById(R.id.tv_text);
            iv_icon = (ImageView) itemView.findViewById(R.id.iv_icon);

            //設置點擊事件
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(onItemClickListener != null){
                        onItemClickListener.onItemClick(v,getLayoutPosition(),datas.get(getLayoutPosition()));
                    }
                }
            });

            //設置監聽
            iv_icon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(onImageViewClickListener != null){
                        onImageViewClickListener.onImageViewClick(v,getLayoutPosition());
                    }
                }
            });
        }
    }
}

  

在Activity中使用自定義的點擊事件

//設置點擊item的點擊事件
myAdapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
    @Override
    public void onItemClick(View view, int position, String content) {
        Toast.makeText(RecyclerViewActivity.this, "content=="+content+",--position=="+position, Toast.LENGTH_SHORT).show();
    }
});

//設置點擊某張圖片的點擊事件
myAdapter.setOnImageViewClickListener(new MyAdapter.OnImageViewClickListener() {
    @Override
    public void onImageViewClick(View view, int position) {
        Toast.makeText(RecyclerViewActivity.this, "position=="+position+",view=="+view.toString(), Toast.LENGTH_SHORT).show();
    }
});

  

6.刪除和增加數據

1_在適配器中新增加添加和刪除兩個方法

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
	
    ........................
	
    public void addData(int position,String content){
        datas.add(position,content);
        notifyItemInserted(position);
    }

    public void removeData(int position){
        datas.remove(position);
        notifyItemRemoved(position);
    }
}

2_Activity中

btn_add.setOnClickListener(new View.OnClickListener() {
	@Override
	public void onClick(View v) {
		myAdapter.addData(0,"Content NetData");
		//定位到第0個位置
		recyclerview.scrollToPosition(0);
	}
});

btn_remove.setOnClickListener(new View.OnClickListener() {
	@Override
	public void onClick(View v) {
		myAdapter.removeData(0);
	}
});

  

  

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved