วิธีใช้งาน Android Pull-to-Refresh (Swipe to Refresh)
ก่อนจะเข้าสู่ตัวอย่าง เราควรทราบว่า Pull to Refresh Layout ใน Android คืออะไร เราสามารถเรียก Pull to Refresh ใน Android ว่า Swipe-to-Refresh เมื่อคุณสไวด์หน้าจอจากบนลงล่าง จะทำการกระทำบางอย่างตาม setOnRefreshListener
ตัวอย่างนี้สาธิตวิธีใช้งาน Android Pull to Refresh
ขั้นตอนที่ 1 - สร้างโปรเจกต์ใหม่ใน Android Studio
ไปที่ File → New Project และกรอกรายละเอียดที่จำเป็นทั้งหมดเพื่อสร้างโปรเจกต์ใหม่
ขั้นตอนที่ 2 - เพิ่มโค้ดใน res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://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 เมื่อคุณสไวด์พาเรนต์เลย์เอาต์ จะเรียก onRefresh() จาก RefreshListener เราอัปเดตข้อความพร้อมจำนวนครั้งที่สไวด์ ดังนี้:
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
i++;
textView.setText("Tutorialspoint.com " + i);
swipeRefresh.setRefreshing(false);
}
});
ลองรันแอปพลิเคชันของคุณ สมมติว่าคุณเชื่อมต่ออุปกรณ์ Android จริงกับคอมพิวเตอร์แล้ว เพื่อรันแอปจาก Android Studio ให้เปิดไฟล์กิจกรรมของโปรเจกต์หนึ่งและคลิกไอคอน Run จากแถบเครื่องมือ เลือกอุปกรณ์มือถือของคุณเป็นตัวเลือก และตรวจสอบอุปกรณ์ซึ่งจะแสดงหน้าจอเริ่มต้น

ในผลลัพธ์ด้านบนแสดงหน้าจอเริ่มต้น ตอนนี้สไวด์จากบนลงล่าง จะอัปเดต TextView ดังภาพด้านล่าง

