📜  在Android中使用ListView使用示例的RecyclerView

📅  最后修改于: 2021-05-09 17:26:27             🧑  作者: Mango

RecyclerView是ListView和GridView的更加灵活和高级的版本。 RecyclerView用于为大型数据集提供有限的窗口,这意味着它可用于显示大量数据,这些数据可以通过维护有限数量的View而非常有效地滚动。在RecyclerView中,我们提供数据并定义每个项目的外观,并且RecyclerView库会在需要时动态创建内容。 RecyclerView是在Android 5.0(API级别21.0)的Material Design中引入的。

RecyclerView如何工作?

  • RecyclerView是一个ViewGroup,其中包含与您的数据相对应的View。它本身就是一个View,因此,它会像添加任何其他UI元素一样被添加到布局文件中。
  • ViewHolder对象用于定义列表中的每个单独元素。创建视图持有人时,它不包含任何内容,RecyclerView会将数据绑定到该视图持有人。 ViewHolder是通过扩展RecyclerView.ViewHolder定义的。
  • 适配器用于将数据绑定到视图。 RecyclerView请求视图,并通过调用适配器中的方法将视图绑定到其数据。可以通过扩展RecyclerView.Adapter来定义适配器。
  • LayoutManager排列列表中的各个元素。它包含由条目数据填充的所有视图的引用。

RecyclerView的LayoutManager类提供了三种类型的内置LayoutManager。

  • LinearLayoutManager:用于显示水平和垂直列表
  • GridLayoutManager:用于以网格形式显示项目
  • StaggeredGridLayoutManager:用于以交错网格的形式显示项目

例子

在此示例中,我们将使用RecyclerView作为ListView。在这里,我们将使用RecyclerView将课程列表及其图像显示为垂直列表。

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

第2步:添加依赖关系

我们将使用RecyclerView作为ListView。因此,我们需要为其添加依赖项。要添加依赖项,请转到Gradle脚本> build.gradle(Module:app)并添加以下依赖项。添加依赖项后,单击立即同步

在继续之前,让我们添加一些颜色属性以增强应用程序栏。转到应用程序> res>值> colors.xml并添加以下颜色属性。

XML
 
    #0F9D58 
    #16E37F 
    #03DAC5 


XML


  
    
    
  


XML


  
    
    
  
    
        
    
  


Java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
  
// Extends the Adapter class to RecyclerView.Adapter
// and implement the unimplemented methods
public class Adapter extends RecyclerView.Adapter {
    ArrayList courseImg, courseName;
    Context context;
  
    // Constructor for initialization
    public Adapter(Context context, ArrayList courseImg, ArrayList courseName) {
        this.context = context;
        this.courseImg = courseImg;
        this.courseName = courseName;
    }
  
    @NonNull
    @Override
    public Adapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // Inflating the Layout(Instantiates list_item.xml
          // layout file into View object)
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
  
        // Passing view to ViewHolder
        Adapter.ViewHolder viewHolder = new Adapter.ViewHolder(view);
        return viewHolder;
    }
  
    // Binding data to the into specified position
    @Override
    public void onBindViewHolder(@NonNull Adapter.ViewHolder holder, int position) {
        // TypeCast Object to int type
        int res = (int) courseImg.get(position);
        holder.images.setImageResource(res);
        holder.text.setText((String) courseName.get(position));
    }
  
    @Override
    public int getItemCount() {
        // Returns number of items 
          // currently available in Adapter
        return courseImg.size();
    }
  
    // Initializing the Views
    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView images;
        TextView text;
  
        public ViewHolder(View view) {
            super(view);
            images = (ImageView) view.findViewById(R.id.courseImg);
            text = (TextView) view.findViewById(R.id.courseName);
        }
    }
}


Java
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import java.util.ArrayList;
import java.util.Arrays;
  
public class MainActivity extends AppCompatActivity {
  
    RecyclerView recyclerView;
  
    // Using ArrayList to store images data
    ArrayList courseImg = new ArrayList<>(Arrays.asList(R.drawable.data_structure, R.drawable.c_plus_plus,
                                                        R.drawable.c_hash, R.drawable.java_script, 
                                                        R.drawable.java, R.drawable.c,
                                                        R.drawable.html, R.drawable.css));
    ArrayList courseName = new ArrayList<>(Arrays.asList("Data Structure", "C++", "C#", "JavaScript", "Java",
                                                         "C-Language", "HTML 5", "CSS"));
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Getting reference of recyclerView
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
  
        // Setting the layout as linear 
          // layout for vertical orientation
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(linearLayoutManager);
  
        // Sending reference and data to Adapter
        Adapter adapter = new Adapter(MainActivity.this, courseImg, courseName);
  
        // Setting Adapter to RecyclerView
        recyclerView.setAdapter(adapter);
    }
}


步骤3:使用activity_main.xml文件

在此步骤中,我们将RecyclerView添加到我们的activity_main.xml文件中,该文件用于显示listItems的数据。转到应用程序> res>布局> activity_main.xml和以下代码段。

XML格式



  
    
    
  

步骤4:创建一个新的布局文件list_item.xml

在此步骤中,我们将为单个列表项视图创建一个新的布局文件。转到应用程序> res>布局>右键单击>新建>布局资源文件,并将其命名为list_item 。 list_item.xml包含一个ImageView和一个TextView,用于填充RecyclerView。

XML格式



  
    
    
  
    
        
    
  

步骤5:创建一个新的适配器类

现在,我们将创建一个Adapter类,该类充当UI组件和数据源之间的桥梁,即courseImg,courseName和RecyclerView。转到应用程序> Java >程序包>右键单击并创建一个新的Java类,并将其命名为Adapter 。下面是为此提供的代码段。

Java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
  
// Extends the Adapter class to RecyclerView.Adapter
// and implement the unimplemented methods
public class Adapter extends RecyclerView.Adapter {
    ArrayList courseImg, courseName;
    Context context;
  
    // Constructor for initialization
    public Adapter(Context context, ArrayList courseImg, ArrayList courseName) {
        this.context = context;
        this.courseImg = courseImg;
        this.courseName = courseName;
    }
  
    @NonNull
    @Override
    public Adapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // Inflating the Layout(Instantiates list_item.xml
          // layout file into View object)
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
  
        // Passing view to ViewHolder
        Adapter.ViewHolder viewHolder = new Adapter.ViewHolder(view);
        return viewHolder;
    }
  
    // Binding data to the into specified position
    @Override
    public void onBindViewHolder(@NonNull Adapter.ViewHolder holder, int position) {
        // TypeCast Object to int type
        int res = (int) courseImg.get(position);
        holder.images.setImageResource(res);
        holder.text.setText((String) courseName.get(position));
    }
  
    @Override
    public int getItemCount() {
        // Returns number of items 
          // currently available in Adapter
        return courseImg.size();
    }
  
    // Initializing the Views
    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView images;
        TextView text;
  
        public ViewHolder(View view) {
            super(view);
            images = (ImageView) view.findViewById(R.id.courseImg);
            text = (TextView) view.findViewById(R.id.courseName);
        }
    }
}

步骤6:使用MainActivity文件

MainActivity中。在Java类中,我们创建了两个ArrayList来存储courseImg和courseName。这些图像放置在drawable文件夹中( app> res> drawable )。您可以使用任何图像代替这些图像。然后,获取引用RecyclerView并将LayoutManager设置为LinearLayoutManager和Adapter,以在RecyclerView中显示项目。下面是MainActivity的代码。 Java文件。

Java

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import java.util.ArrayList;
import java.util.Arrays;
  
public class MainActivity extends AppCompatActivity {
  
    RecyclerView recyclerView;
  
    // Using ArrayList to store images data
    ArrayList courseImg = new ArrayList<>(Arrays.asList(R.drawable.data_structure, R.drawable.c_plus_plus,
                                                        R.drawable.c_hash, R.drawable.java_script, 
                                                        R.drawable.java, R.drawable.c,
                                                        R.drawable.html, R.drawable.css));
    ArrayList courseName = new ArrayList<>(Arrays.asList("Data Structure", "C++", "C#", "JavaScript", "Java",
                                                         "C-Language", "HTML 5", "CSS"));
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Getting reference of recyclerView
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
  
        // Setting the layout as linear 
          // layout for vertical orientation
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(linearLayoutManager);
  
        // Sending reference and data to Adapter
        Adapter adapter = new Adapter(MainActivity.this, courseImg, courseName);
  
        // Setting Adapter to RecyclerView
        recyclerView.setAdapter(adapter);
    }
}

输出:在模拟器上运行

在Android中使用ListView的RecyclerView

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!