📜  在Android中使用RecyclerView刷新示例

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

SwipeRefreshLayout窗口小部件用于实现从刷新到刷新的用户界面设计模式。用户使用垂直轻扫手势刷新视图内容的位置。垂直滑动可通过SwipeRefreshLayout小部件检测到,并显示不同的进度条并触发应用程序中的回调方法。为了使用此行为,我们需要使用SwipeRefreshLayout小部件作为ListView或GridView的父级。这些材料设计UI模式可以在Gmail,Youtube,Facebook,Instagram等应用程序中看到。它允许用户手动刷新应用程序。 SwipeRefreshLayout类包含一个名为OnRefreshListener的侦听。想要使用此侦听器的类应实现SwipeRefreshLayout.OnRefreshListener接口。在垂直向下滑动手势时,将触发此侦听器,并调用onRefresh()方法,并且可以根据需要重写此方法。

例子

在此示例中,我们将数据存储到用于填充RecyclerView的ArrayList中。每当调用onRefresh()方法时,都会重新排列ArrayList数据。下面给出了一个示例GIF,以使我们对本文中要做的事情有一个了解。注意,我们将使用Java语言实现该项目。

在Android中使用RecyclerView刷新

分步实施

步骤1:创建一个新项目

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

步骤2:添加依赖项

我们将使用RecyclerView和SwipeRefreshLayout。因此,我们需要为其添加依赖项。要添加这些依赖项,请转到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 images, text;
    Context context;
  
    // Constructor for initialization
    public Adapter(Context context, ArrayList images, ArrayList text) {
        this.context = context;
        this.images = images;
        this.text = text;
    }
  
    @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) images.get(position);
        holder.images.setImageResource(res);
        holder.text.setText((CharSequence) text.get(position));
    }
  
    @Override
    public int getItemCount() {
        // Returns number of items currently available in Adapter
        return text.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.imageView);
            text = (TextView) view.findViewById(R.id.textView);
        }
    }
}


Java
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
  
public class MainActivity extends AppCompatActivity {
    SwipeRefreshLayout swipeRefreshLayout;
    RecyclerView recyclerView;
      
    // Using ArrayList to store images and text data
    ArrayList images = new ArrayList<>(Arrays.asList(R.drawable.facebook, R.drawable.twitter,
                    R.drawable.instagram, R.drawable.linkedin, R.drawable.youtube, R.drawable.whatsapp));
    ArrayList text = new ArrayList<>(Arrays.asList("Facebook", "Twitter", "Instagram", "LinkedIn", "Youtube", "Whatsapp"));
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Getting reference of swipeRefreshLayout and recyclerView
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
          
        // Setting the layout as Linear for vertical orientation to have swipe behavior
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(linearLayoutManager);
          
        // Sending reference and data to Adapter
        Adapter adapter = new Adapter(MainActivity.this, images, text);
          
        // Setting Adapter to RecyclerView
        recyclerView.setAdapter(adapter);
          
        // SetOnRefreshListener on SwipeRefreshLayout
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipeRefreshLayout.setRefreshing(false);
                RearrangeItems();
            }
        });
    }
  
    public void RearrangeItems() {
        // Shuffling the data of ArrayList using system time
        Collections.shuffle(images, new Random(System.currentTimeMillis()));
        Collections.shuffle(text, new Random(System.currentTimeMillis()));
        Adapter adapter = new Adapter(MainActivity.this, images, text);
        recyclerView.setAdapter(adapter);
    }
}


步骤3:使用activity_main.xml文件

在此步骤中,我们将创建SwipeRefreshLayout并将RecyclerView添加到其中。转到应用程序> res>布局> activity_main.xml并添加以下代码段。

XML格式



  
  
    
  

步骤4:为RecyclerView的列表项创建一个新的布局文件list_item.xml。

转到应用程序> res>布局>右键单击>新建>布局资源文件,并将其命名为list_itemlist_item.xml布局文件包含一个ImageView和一个TextView,用于填充RecyclerView的行。

XML格式



  
    
    
  
    
  

步骤5:为RecyclerView创建适配器类

现在,我们将创建一个适配器。将通过ViewHolder扩展RecyclerView.Adapter的Java类。转到应用程序> Java >程序包>右键单击并创建一个新的Java类,并将其命名为Adapter 。在适配器类中,我们将覆盖 onCreateViewHolder()方法将膨胀list_item.xml布局并将其传递给View Holder。然后是onBindViewHolder()方法,在该方法中,我们借助View Holder将数据设置为Views。以下是Adapter的代码段。 Java类。

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 images, text;
    Context context;
  
    // Constructor for initialization
    public Adapter(Context context, ArrayList images, ArrayList text) {
        this.context = context;
        this.images = images;
        this.text = text;
    }
  
    @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) images.get(position);
        holder.images.setImageResource(res);
        holder.text.setText((CharSequence) text.get(position));
    }
  
    @Override
    public int getItemCount() {
        // Returns number of items currently available in Adapter
        return text.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.imageView);
            text = (TextView) view.findViewById(R.id.textView);
        }
    }
}

步骤6:使用MainActivity。 Java文件

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

Java

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
  
public class MainActivity extends AppCompatActivity {
    SwipeRefreshLayout swipeRefreshLayout;
    RecyclerView recyclerView;
      
    // Using ArrayList to store images and text data
    ArrayList images = new ArrayList<>(Arrays.asList(R.drawable.facebook, R.drawable.twitter,
                    R.drawable.instagram, R.drawable.linkedin, R.drawable.youtube, R.drawable.whatsapp));
    ArrayList text = new ArrayList<>(Arrays.asList("Facebook", "Twitter", "Instagram", "LinkedIn", "Youtube", "Whatsapp"));
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Getting reference of swipeRefreshLayout and recyclerView
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
          
        // Setting the layout as Linear for vertical orientation to have swipe behavior
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(linearLayoutManager);
          
        // Sending reference and data to Adapter
        Adapter adapter = new Adapter(MainActivity.this, images, text);
          
        // Setting Adapter to RecyclerView
        recyclerView.setAdapter(adapter);
          
        // SetOnRefreshListener on SwipeRefreshLayout
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipeRefreshLayout.setRefreshing(false);
                RearrangeItems();
            }
        });
    }
  
    public void RearrangeItems() {
        // Shuffling the data of ArrayList using system time
        Collections.shuffle(images, new Random(System.currentTimeMillis()));
        Collections.shuffle(text, new Random(System.currentTimeMillis()));
        Adapter adapter = new Adapter(MainActivity.this, images, text);
        recyclerView.setAdapter(adapter);
    }
}

输出:

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