如何在 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 中執行應用程式,請開啟您的一個專案活動檔案並單擊執行 工具欄中的圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕:

上面的結果顯示了初始螢幕,現在從上到下滑動將更新文字檢視,如下所示:


點選 此處 下載專案程式碼

更新於:2019年7月30日

515 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告