如何在 Android 中实现下拉刷新?
在进入示例之前,我们应该了解 Android 中的下拉刷新布局是什么。我们可以将 Android 中的下拉刷新称为滑动刷新。当您从上到下滑动屏幕时,它将根据 setOnRefreshListener 执行某些操作。
此示例演示如何在 Android 中实现下拉刷新。
步骤 1 − 在 Android Studio 中创建一个新项目,转到文件 ⇒ 新建项目,并填写所有必需的详细信息以创建新项目。
步骤 2 − 将以下代码添加到 res/layout/activity_main.xml。
<?xml version = "1.0" encoding = "utf-8"?> <android.support.v4.widget.SwipeRefreshLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:id = "@+id/swipeRefresh" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity"> <LinearLayout android:layout_width = "wrap_content" android:gravity = "center" android:layout_height = "wrap_content"> <TextView android:id = "@+id/text" android:textSize = "30sp" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "Hello World!"/> </LinearLayout> </android.support.v4.widget.SwipeRefreshLayout>
在上面的代码中,我们将 swipeRefreshLayout 作为父布局,当用户滑动布局时,它可以刷新子视图。
步骤 3 − 将以下代码添加到 src/MainActivity.java
package com.example.andy.myapplication;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
SwipeRefreshLayout swipeRefresh;
static int i = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = findViewById(R.id.text);
swipeRefresh = findViewById(R.id.swipeRefresh);
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
i++;
textView.setText("Tutorialspoint.com "+i);
swipeRefresh.setRefreshing(false);
}
});
}
}在上面的代码中,我们使用了 onRefreshListener,当您滑动父布局时,它将调用 RefreshListener 中的 onRefresh() 方法,我们正在使用滑动计数更新文本,如下所示:
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
i++;
textView.setText("Tutorialspoint.com "+i);
swipeRefresh.setRefreshing(false);
}
});让我们尝试运行您的应用程序。我假设您已将您的实际 Android 移动设备连接到您的计算机。要在 Android Studio 中运行应用程序,请打开您的一个项目活动文件并单击运行
工具栏中的图标。选择您的移动设备作为选项,然后检查您的移动设备,它将显示您的默认屏幕:

上面的结果显示了初始屏幕,现在从上到下滑动将更新文本视图,如下所示:


点击 此处 下载项目代码
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP