Simple use of RecyclerView

Since Android 5.0, googlet has launched a RecyclerView control, which is a new component in the support-v7 package. It is a powerful sliding component. Compared with the classic ListView, it also has the function of item recycling and reuse. RecyclerView is equivalent to ListView. upgraded version.

RecyclerView encapsulates the recycling and reuse of ViewHolder, that is to say, RecyclerView standardizes ViewHolder, writing Adapter is for ViewHolder instead of View, and the reuse logic is encapsulated, making it easier to write.

RecyclerView provides a plug-in experience, highly decoupled, and extremely flexible. RecyclerView specially extracts the corresponding class for the display of an Item to control the display of the Item, making it particularly scalable.

Introduce RecyclerVIew

compile 'com.android.support:recyclerview-v7:25.1.0'

Create layout file

main layout file
/*activity_main.xml*/
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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.manu.mrecyclerview.MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v7.widget.RecyclerView>
</LinearLayout>

Item layout file
/*item.xml*/
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp">
    <TextView
        android:id="@+id/tv_recycle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="data"
        android:background="#cac3c3"
        android:padding="10dp"
        android:textSize="20sp"/>
</LinearLayout>

Create Adapter

The Adapter of RecyclerView is a little more complicated to set up than the Adapter of ListView. This is also the embodiment of the high decoupling of RecyclerView. Although the code is a little more complicated, it has good scalability. Here are three ways to implement the Adapter of RecyclerView:

onCreateViewHolder()

This method is mainly to load a View for each Item, but this method returns a ViewHolder. This method directly encapsulates the View in the ViewHolder, and then we face the instance of ViewHolder. This ViewHolder is also written by itself, but it does not need to be like ListView calls convertView.setTag(vh) and convertView.getTag().

onBindViewHolder()

This method is mainly used to bind data to the View, and directly provide a ViewHolder instead of convertView.

getItemCount()

This method returns the total number of options.

Adapter code
/**
 * Created by jzman on 2017/5/13 0013.
 */
public class RvAdapter extends RecyclerView.Adapter<RvAdapter.DataViewHolder>{
    private Context mContext;
    private ArrayList<String> mList;

    public RvAdapter() {}

    public RvAdapter(Context mContext, ArrayList<String> mList) {
        this.mContext = mContext;
        this.mList = mList;
    }

    //用于创建ViewHolder
    @Override
    public DataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item,null);
        //使用代码设置宽高(xml布局设置无效时)
        view.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        DataViewHolder holder = new DataViewHolder(view);
        return holder;
    }
    //绑定数据
    @Override
    public void onBindViewHolder(DataViewHolder holder, int position) {
        holder.tv_data.setText(mList.get(position));
    }
    //数据总数
    @Override
    public int getItemCount() {
        return mList.size();
    }

    //创建ViewHolder
    public static class DataViewHolder extends RecyclerView.ViewHolder{
        TextView tv_data;
        public DataViewHolder(View itemView) {
            super(itemView);
            tv_data = (TextView) itemView.findViewById(R.id.tv_recycle);
        }
    }

When using the StaggeredGridLayoutManager manager, the Adapter reference is as follows:

/**
 * Created by jzman on 2017/5/13 0013.
 * RecycleView的Adapter
 */
public class RvAdapter extends RecyclerView.Adapter<RvAdapter.DataViewHolder>{
    private Context mContext;
    private RecyclerView recyclerView;
    private ArrayList<String> mList;
    private ArrayList<Integer> mHeight;

    public RvAdapter() {}

    public RvAdapter(Context mContext, ArrayList<String> mList) {
        this.mContext = mContext;
        this.mList = mList;
    }

    /**
     * 初始化每个Item的高度(瀑布流效果)
     * @return
     */
    public ArrayList<Integer> initHeight(){
        mHeight = new ArrayList<>();
        for (int i=0;i<mList.size();i++){
            mHeight.add((int) (Math.random()*300)+200);
        }
        return mHeight;
    }

    /**
     * 用于创建ViewHolder
     * @param parent
     * @param viewType
     * @return
     */
    @Override
    public DataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item,null);
        //使用代码设置宽高(xml布局设置无效时)
        view.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        DataViewHolder holder = new DataViewHolder(view);
        return holder;
    }

    /**
     * 绑定数据
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(DataViewHolder holder, int position) {
        //设置每个Item的高度
        ViewGroup.LayoutParams h = holder.tv_data.getLayoutParams();
        h.height = mHeight.get(position);
        holder.tv_data.setText(mList.get(position));
    }

    /**
     * 选项总数
     * @return
     */
    @Override
    public int getItemCount() {
        return mList.size();
    }

    /**
     * 创建ViewHolder
     */
    public static class DataViewHolder extends RecyclerView.ViewHolder{
        TextView tv_data;
        public DataViewHolder(View itemView) {
            super(itemView);
            tv_data = (TextView) itemView.findViewById(R.id.tv_recycle);
        }
    }
    /**
     *   将RecycleView附加到Adapter上
     */
    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        this.recyclerView= recyclerView;
        //初始化每个Item的高度
        initHeight();
    }
    /**
     *   将RecycleView从Adapter解除
     */
    @Override
    public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
        super.onDetachedFromRecyclerView(recyclerView);
        this.recyclerView = null;
    }
}

MainActivity

/**
 * Created by jzman on 2017/5/13 0013.
 */
public class MainActivity extends AppCompatActivity {
    private RecyclerView rv;
    RvAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rv = (RecyclerView) findViewById(R.id.rv);
        //设置布局管理器
        rv.setLayoutManager(new LinearLayoutManager(this));//线性
//        rv.setLayoutManager(new GridLayoutManager(this,4));//线性
//        rv.setLayoutManager(new StaggeredGridLayoutManager(4,StaggeredGridLayoutManager.VERTICAL));//线性
        adapter = new RvAdapter(this,initData());
        rv.setAdapter(adapter);
    }
    public static ArrayList<String> initData(){
        ArrayList<String> arrayList = new ArrayList<>();
        for (int i=0;i<50;i++){
            arrayList.add("第"+i+"条数据");
        }
        return arrayList;
    }
}

display effect

LinearLayoutManager GridLayoutManager StaggeredGridLayoutManager
image image image

If you find it helpful, you can follow the public account: jzman-blog to communicate and learn together.

Enter image description")

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324896979&siteId=291194637