1.使用步骤

1.在build.gradle文件中添加RecyclerView的依赖,例

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

2.布局中使用RecyclerView

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

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

3.创建RecycleView的ItemView的布局

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:padding="16dp">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_item_number"
        style="@style/TextAppearance.AppCompat.Title"
        android:fontFamily="monospace"
        android:textSize="42sp"/>
</FrameLayout>

4.创建继承自RecyclerView.ViewHolder的自定义ViewHolder类,并实现自身的构造方法

class NumberViewHolder extends RecyclerView.ViewHolder {
        public NumberViewHolder(View itemView) {
            super(itemView);
        }
    }

5.在自定义的ViewHolder类中创建对应ItemView布局元素的变量,并在构造函数中将变量进行findViewById的初始化

    /**
     * Cache of the children views for a list item.
     */
    class NumberViewHolder extends RecyclerView.ViewHolder {

        // Will display the position in the list, ie 0 through getItemCount() - 1
        TextView listItemNumberView;

        /**
         * Constructor for our ViewHolder. Within this constructor, we get a reference to our
         * TextViews and set an onClickListener to listen for clicks. Those will be handled in the
         * onClick method below.
         * @param itemView The View that you inflated in
         *                 {@link GreenAdapter#onCreateViewHolder(ViewGroup, int)}
         */
        public NumberViewHolder(View itemView) {
            super(itemView);

            listItemNumberView = (TextView) itemView.findViewById(R.id.tv_item_number);
        }

        /**
         * A method we wrote for convenience. This method will take an integer as input and
         * use that integer to display the appropriate text within a list item.
         * @param listIndex Position of the item in the list
         */
        void bind(int listIndex) {
            listItemNumberView.setText(String.valueOf(listIndex));
        }
    }

6.创建继承自RecyclerView.Adapter的自定义Adapter类,父类后添加泛型,泛型填入之前创建的ViewHolder。

7.自定义Adapter类复写父类的onCreateViewHolder()方法、onBindViewHolder()方法、getItemCount()方法。

results matching ""

    No results matching ""