Android L SDK发布的,新API中最有意思的就是RecyclerView (后面为RV) 和 CardView了, 按照官方的说法, RV 是一个ListView 的一个更高级更灵活的一个版本, 可以自定义的东西太多了。以前会不会觉得写一个Horizontal ListView 都觉得挺吃力的,但是如果你看过RV的话,你就会觉得这也太简单了吧。 废话不多,下面转入正题。
今天这里主要讲述的是 RV 简单用法:
1.跟ListView 一样 需要一个 Adapter
2.跟ListView 一样 需要一个 ViewHolder
3.有点不同了, 需要一个LayoutManager
详细过程看代码吧:
package com.jarrah.demo;
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
public abstract class RecyclerViewActivity extends ActionBarActivity{
protected RecyclerView mRecyclerView;
protected Adapter<String> mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRecyclerView = new RecyclerView(this);
setContentView(mRecyclerView);
//配置RecyclerView 可以提高执行效率, 前提你要知道有多少不变的item
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
//初始化适配器
mAdapter = new Adapter<String>() {
@Override
public ViewHolder<String> onCreateViewHolder(ViewGroup group,
int position) {
return newViewHolder(group, position);
}
};
mRecyclerView.setAdapter(mAdapter);
//设置一个垂直方向的layout manager
int orientation = LinearLayoutManager.VERTICAL;
mRecyclerView.setLayoutManager(getLayoutManager(orientation));
}
protected LinearLayoutManager getLayoutManager(int orientation) {
return new LinearLayoutManager(this, orientation, false);
}
/**
* 实例化一个ViewHolder
* @param group
* @param position
* @return
*/
public abstract ViewHolder<String> newViewHolder(ViewGroup group, int position);
public static abstract class Adapter<T> extends RecyclerView.Adapter<ViewHolder<T>> {
private ArrayList<T> mList;
public T getItem(int position) {
return mList == null ? null : mList.get(position);
}
@Override
public int getItemCount() {
return mList == null ? 0 : mList.size();
}
@Override
public void onBindViewHolder(
ViewHolder<T> vh, int position) {
vh.onBind(getItem(position), vh.itemView);
}
public void setData(ArrayList<T> data) {
mList = data;
notifyDataSetChanged();
}
}
public static abstract class ViewHolder<T> extends RecyclerView.ViewHolder {
public ViewHolder(View v) {
super(v);
}
/**
* view holder 绑定数据
* @param data
* @param v
*/
public abstract void onBind(T data, View v);
}
}
下面是demo activity
package com.jarrah.demo;
import java.util.ArrayList;
import java.util.Arrays;