欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

RecyclerView的简单使用

程序员文章站 2022-06-05 12:39:21
...

以下代码均来自郭霖的《第一行代码》第2版,想了解详细内容的可以去看原书。

1、RecyclerView

RecyclerView 是一个增强版的ListView,不仅可以实现和ListView同样的效果,还优化了ListView中存在的各种不足之处。

ResyslerView 能够实现横向滚动,瀑布流布局等。

2、竖向滚动

仍然先介绍竖向滚动,代码量与ListView差不多,但是逻辑更加清晰,功能分块更加明确。

准备工作: 需要先在build.gradle文件中添加相应的依赖库。
(是在app文件夹下的build.gradle文件!!!)

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    implementation 'com.android.support:recyclerview-v7:26.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

第二步:在layout_main.xml中添加RecyclerView控件。

<?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"
    android:orientation="vertical"
    tools:context="com.example.admin.recycleviewtest.MainActivity">

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

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

</LinearLayout>

第三步:与ListView的步骤差不多,同样是新建item的类,布局文件,自定义一个Adapter,主要区别在Adapter上。
(其余文件代码很简单,主要解释Adapter.java)

public class AnimalAdapter extends RecyclerView.Adapter<AnimalAdapter.ViewHolder> {
    private ArrayList<Animal> mAnimals;

    public AnimalAdapter(ArrayList<Animal> animals) {
        mAnimals = animals;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        private ImageView mImageView;
        private TextView mTextView;

        public ViewHolder(View v) {
            super(v);
            mImageView = v.findViewById(R.id.image);
            mTextView = v.findViewById(R.id.name);
        }
    }

    @Override
    public AnimalAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.layout_animal_item, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(AnimalAdapter.ViewHolder holder, int position) {
        Animal animal = mAnimals.get(position);
        holder.mImageView.setImageResource(animal.getImageId());
        holder.mTextView.setText(animal.getName());
    }

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

AnimalAdapter 继承 RecyclerView.Adapter< AnimalAdapter.ViewHolder >,这里需要现在AnimalAdapter中定义内部类ViewHolder并继承RecyclerView.ViewHolder
这里的ViewHolderListView中用来优化的ViewHolder有一些区别,这里的ViewHolder中需要定义构造函数,同时找到item布局中的控件id并赋值。
同时AnimalAdapter类需要重写三个方法:onCreateViewHolder(),onBindViewHolder(),getItemCount()。

  • onCreateViewHolder( ) : 用于创建ViewHolder实例。
  • onBindViewHolder( ) : 对RecyclerView的子项进行赋值。
  • getItemCount( ) : 数据源的长度。

layout_animal_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    >

    <ImageView
        android:id="@+id/image"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@drawable/dragon"
        />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:text="dragon"
        android:layout_marginTop="8dp"
        android:layout_marginLeft="5dp"
        />

</LinearLayout>

Animal.java

package com.example.admin.recycleviewtest;

public class Animal {
    private int imageId;
    private String name;

    public Animal(int imageId, String name) {
        this.imageId = imageId;
        this.name = name;
    }

    public int getImageId() {
        return imageId;
    }

    public void setImageId(int imageId) {
        this.imageId = imageId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

**第三步:**MainAcitivity实例化RecyclerView。

public class MainActivity extends AppCompatActivity {

    private ArrayList<Animal> mAnimalArrayList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initAnimal();
        RecyclerView recyclerView = findViewById(R.id.recyclerView);

        //指定RecyclerView的布局方式,这里是线性布局。
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
        recyclerView.setLayoutManager(linearLayoutManager);

        AnimalAdapter animalAdapter = new AnimalAdapter(mAnimalArrayList);
        recyclerView.setAdapter(animalAdapter);
    }

    public void initAnimal() {
        for(int i = 0; i < 3; i++) {
            Animal bear = new Animal(R.drawable.bear, "bear");
            mAnimalArrayList.add(bear);
            Animal dog = new Animal(R.drawable.dog, "dog");
            mAnimalArrayList.add(dog);
            Animal longmao = new Animal(R.drawable.longmao, "longmao");
            mAnimalArrayList.add(longmao);
            Animal dragon = new Animal(R.drawable.dragon, "dragon");
            mAnimalArrayList.add(dragon);
            Animal bird = new Animal(R.drawable.bird, "bird");
            mAnimalArrayList.add(bird);
        }
    }
}

RecyclerView的简单使用

3、横向滚动

只需要修改一下item布局与LinearLayoutManager的方向。

        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

layout_animal_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_marginLeft="5dp"
    >

    <ImageView
        android:id="@+id/image"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@drawable/dragon"
        />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="dragon"
        />

</LinearLayout>

RecyclerView的简单使用

4、瀑布流布局

需要将LinearLayoutManager改为StaggeredGridLayoutManager,同时修改布局文件与initAnimal( )函数修改文本长短。

        //这里设置3列,垂直分布的瀑布流布局。
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(
                3, StaggeredGridLayoutManager.VERTICAL);
public void initAnimal() {
        for(int i = 0; i < 3; i++) {
            Animal bear = new Animal(R.drawable.bear, getRandomLength("bear"));
            mAnimalArrayList.add(bear);
            Animal dog = new Animal(R.drawable.dog, getRandomLength("dog"));
            mAnimalArrayList.add(dog);
            Animal longmao = new Animal(R.drawable.longmao, getRandomLength("longmao"));
            mAnimalArrayList.add(longmao);
            Animal dragon = new Animal(R.drawable.dragon, getRandomLength("dragon"));
            mAnimalArrayList.add(dragon);
            Animal bird = new Animal(R.drawable.bird, getRandomLength("bird"));
            mAnimalArrayList.add(bird);
        }
    }

    public String getRandomLength(String s) {
        Random random = new Random();
        int length = random.nextInt(20) + 1;
        StringBuilder builder = new StringBuilder();
        for(int i = 0; i < length; i++) {
            builder.append(s);
        }
        return builder.toString();
    }
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_marginLeft="5dp"
    >

    <ImageView
        android:id="@+id/image"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@drawable/dragon"
        />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:text="dragon"
        />

</LinearLayout>

RecyclerView的简单使用

数据分布是从左往右!!!

5、点击事件

RecyclerView中并没有类似于ListView的setOnItemClickListener( ),需要自己为所需控件添加事件监听。

public class AnimalAdapter extends RecyclerView.Adapter<AnimalAdapter.ViewHolder> {
    private ArrayList<Animal> mAnimals;

    public AnimalAdapter(ArrayList<Animal> animals) {
        mAnimals = animals;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        private ImageView mImageView;
        private TextView mTextView;
        private View mAnimalView;

        public ViewHolder(View v) {
            super(v);
            mAnimalView = v;
            mImageView = v.findViewById(R.id.image);
            mTextView = v.findViewById(R.id.name);
        }
    }

    @Override
    public AnimalAdapter.ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.layout_animal_item, parent, false);
        final ViewHolder holder = new ViewHolder(view);

        holder.mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                Toast.makeText(v.getContext(),
                        "You click photo : " + mAnimals.get(position).getName(),
                        Toast.LENGTH_SHORT).show();
            }
        });

        holder.mAnimalView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int postion = holder.getAdapterPosition();
                Toast.makeText(v.getContext(),
                        "You click view : " + mAnimals.get(postion).getName(),
                        Toast.LENGTH_SHORT).show();
            }
        });

        return holder;
    }

    @Override
    public void onBindViewHolder(AnimalAdapter.ViewHolder holder, int position) {
        Animal animal = mAnimals.get(position);
        holder.mImageView.setImageResource(animal.getImageId());
        holder.mTextView.setText(animal.getName());
    }

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

这里设置了两个点击事件,一个为imageView,一个为整个子数据的View。
这里没有为TextView设置点击事件,所以会被子项的最外层布局所捕获。

RecyclerView的简单使用

RecyclerView的简单使用

相关标签: Android