RecyclerView 入門教程(超詳細)

RecyclerView 入門教程

本篇參照hongyang大神的博客, 推薦看看原文, 更加精彩
http://blog.csdn.net/lmj623565791/article/details/45059587

引入RecyclerView包

1. AndroidStudio

確保 android support 包更新到最新版本
這裏寫圖片描述
在model的build.gradle中添加依賴, 23表示當前使用的編譯android版本
這裏寫圖片描述
然後sync procjet, 就可以在project視圖下看到包已經導入
這裏寫圖片描述

2. Eclipse

首先還是確認android support 包已經更新的到最新, 然後eclipse -> import projects-> android projects ->
導入RecyclerView路徑:
<Your SDK>\extras\android\support\v7\recyclerview
這裏寫圖片描述
一定記住選copy到workspace, 否則後面引入library時無法找到
看項目結構:
這裏寫圖片描述
將項目設置成library:
這裏寫圖片描述
在自己的項目中引入library:
這裏寫圖片描述
然後就導入成功了:
這裏寫圖片描述

使用RecyclerView先實現ListView效果

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private RecyclerView mRecyclerView;
    private MyAdapter mMyAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRecyclerView = (RecyclerView) findViewById(R.id.rv_main);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mMyAdapter = new MyAdapter(MainActivity.this, initData());
        mRecyclerView.setAdapter(mMyAdapter);
    }

    private List<String> initData() {
        List<String> datas = new ArrayList<String>();
        for (int i = 0; i <= 100; i++) {
            datas.add("item:" + i);
        }
        return datas;
    }
}

MyAdapter.java

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

    private static final String TAG = "MyAdapter";
    private List<String> datas;
    private LayoutInflater inflater;

    public MyAdapter(Context context, List<String> datas) {
        this.datas = datas;
        inflater = LayoutInflater.from(context);
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        private TextView title;

        public MyViewHolder(View itemView) {
            super(itemView);
            title = (TextView) itemView.findViewById(R.id.rv_main_item_title);
        }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Log.e(TAG, "create a new item");
        MyViewHolder holder = new MyViewHolder(inflater.inflate(R.layout.rv_main_item, parent, false));
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Log.e(TAG, "set value to item:" + position);
        holder.title.setText(datas.get(position));
    }

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

activity_main.xml

<?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="org.xm.recyclerviewsimple.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v7.widget.RecyclerView>

</RelativeLayout>

rv_main_item.xml

<?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="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/rv_main_item_title"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:text="T.T"
        android:textSize="20sp" />

</RelativeLayout>

現在的效果:
這裏寫圖片描述

給每個item添加一條分解線:

1. 不需要添加分割線, 通過背景設置顯示間隔

爲每個item添加背景白色,並且設置間隔1dp
rv_main_item.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#ffffff"
    android:layout_marginBottom="1dp"
    android:orientation="vertical">

    ...

</RelativeLayout>

再給RecyclerView添加黑色背景
activity_main.xml

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_main"
        android:background="#000000"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v7.widget.RecyclerView>

分割線就顯示出來了
這裏寫圖片描述

2. 自定義分割線

自定義drawable文件
rm_main_item_divicer.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:centerColor="#ff00ff00"
        android:endColor="#ff0000ff"
        android:startColor="#ffff0000"
        android:type="linear" />
    <size android:height="1dp"/>
</shape>

自定義分割線

class MyItemDivider extends RecyclerView.ItemDecoration {
    private Drawable mDrawable;

    public MyItemDivider(Context context, int resId) {
        mDrawable = context.getResources().getDrawable(resId);
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int left = parent.getPaddingLeft();
        int right = parent.getWidth() - parent.getPaddingRight();
        int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = parent.getChildAt(i);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            int top = child.getBottom() + params.bottomMargin;
            int bottom = top + mDrawable.getIntrinsicHeight();
            mDrawable.setBounds(left, top, right, bottom);
            mDrawable.draw(c);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        outRect.set(0, 0, 0, mDrawable.getIntrinsicWidth());
    }
}

然後添加到RecyclerView中:
mRecyclerView.addItemDecoration(new MyItemDivider(this,R.drawable.rv_main_item_divider));

效果:
這裏寫圖片描述

修改佈局管理器

上面的代碼佈局管理器使用的是LinerlayoutManager, 如果這個時候我們將佈局管理器修改爲 GridLayoutManager 會是什麼效果呢?

// mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setLayoutManager(new GridLayoutManager(this,3));

這裏寫圖片描述
確實很屌, 就一行代碼,就改成了gridview. 注意剛剛寫得分割線, 如果修改爲 grideview之後是不能用的,所以這裏我使用的是 利用背景添加分割線的方式, 很簡單了, 只需要同時添加 margin_bottom 和 margin_right 以及修改背景顏色即可.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginRight="1px"
    android:layout_marginTop="1px"
    android:background="#ffffff"
    android:orientation="vertical">

    ...

</RelativeLayout>

如果使用 StaggeredGridLayoutManager, 可以很容易實現瀑布流佈局

// mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// mRecyclerView.setLayoutManager(new GridLayoutManager(this,3));
mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL));

貼一個簡單的效果圖:
這裏寫圖片描述
實現方法簡單, 在onBindViewHolder中使用隨機數來產生iteam的高度:

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    Log.e(TAG, "set value to item:" + position);
    holder.title.setText(datas.get(position));

    int height = Math.abs((new Random().nextInt()) % 300);
    if (height < 200) {
        height += 200;
    }
    holder.title.setHeight(height);
}

注意將原來的item配置layout文件修改一下寬高:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="1px"
    android:layout_marginTop="1px"
    android:background="#ffffff"
    android:orientation="vertical">

    <TextView
        android:id="@+id/rv_main_item_title"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="T.T"
        android:textSize="20sp" />

</RelativeLayout>

添加點擊事件和長按事件

首先在 MyAdapter中定義兩個click事件接口, 以及setter:

public interface OnItemClickListener {
    public void onClick(View parent, int position);
}

public interface OnItemLongClickListener {
    public boolean onLongClick(View parent, int position);
}

public void setOnItemClickListener(OnItemClickListener l) {
    this.mOnItemClickListener = l;
}

public void setOnItemLongClickListener(OnItemLongClickListener l) {
    this.mOnItemLongClickListener = l;
}

在onBindViewHolder中設置事件響應:

@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
    //...

    // 設置事件響應
    if (mOnItemClickListener != null) {
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int pos = holder.getLayoutPosition();
                mOnItemClickListener.onClick(holder.itemView, pos);
            }
        });
    }
    if (mOnItemLongClickListener != null) {
        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                int pos = holder.getLayoutPosition();
                mOnItemLongClickListener.onLongClick(holder.itemView, pos);
                return false;
            }
        });
    }
}

在MainActivity中添加事件:

mMyAdapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
    @Override
    public void onClick(View parent, int position) {
        mMyAdapter.addData(position,"add item:"+position);
        mMyAdapter.notifyItemInserted(position);
    }
});
mMyAdapter.setOnItemLongClickListener(new MyAdapter.OnItemLongClickListener() {
    @Override
    public boolean onLongClick(View parent, int position) {
        mMyAdapter.removeData(position);
        mMyAdapter.notifyItemRemoved(position);
        return false;
    }
});

注意:
這裏點擊事件的操作是再添加一個item, 長按事件是刪除一個item. 我們還需要在MyAdapter中添加 addData(), 和removeData() 兩個方法:

    public void addData(int position, String content){
        datas.add(position,content);
    }

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

然後配合自帶的 notifyItemInserted(), 和notifyItemRemoved() 可以很輕鬆實現添加item和刪除item炒作. 趕緊試試吧!

最後的最後, 再給每個item添加上press的selector, 增加用戶體驗:
定義rv_main_item_selector.xml文件

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/colorPrimary" />
    <item android:drawable="@android:color/white" />
</selector>

將item的背景設置成selector:
android:background="@drawable/rv_main_item_selector"
搞定了

最後

附上代碼下載地址:
http://download.csdn.net/detail/u013647382/9575291

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章