Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Triển khai Pull-to-Refresh (Vuốt để làm mới) trong Android

Khái niệm

Pull-to-Refresh (SwipeRefreshLayout): Vuốt từ trên xuống dưới để kích hoạt làm mới nội dung. Thường dùng cho List/RecyclerView.

Cách làm

Bước 1: Tạo project

Bước 2: Layout activity_main.xml - Bọc content trong SwipeRefreshLayout

<android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="..."
    android:id="@+id/swipeRefresh"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <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>

Bước 3: MainActivity.java

public class MainActivity extends AppCompatActivity {
    SwipeRefreshLayout swipeRefresh;
    static int count = 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(() -> {
            count++;
            textView.setText("Tutorialspoint.com " + count);
            swipeRefresh.setRefreshing(false); // Tắt spinner
        });
    }
}

Luồng xử lý:

  1. User vuốt xuống → spinner xoay tròn xuất hiện.
  2. onRefresh() được gọi.
  3. Xử lý logic (load data, update UI...).
  4. Gọi setRefreshing(false) để ẩn spinner.

Kết quả

Màn hình ban đầu:

Triển khai Pull-to-Refresh (Vuốt để làm mới) trong Android

Vuốt xuống → text cập nhật, spinner biến mất:

Triển khai Pull-to-Refresh (Vuốt để làm mới) trong Android

Vuốt tiếp → đếm tăng:

Triển khai Pull-to-Refresh (Vuốt để làm mới) trong Android

Mẹo

  • Với RecyclerView/ListView: đặt SwipeRefreshLayout làm parent.
  • Tùy chỉnh màu spinner: swipeRefresh.setColorSchemeResources(R.color.color1, R.color.color2...).
  • Bật/tắt programmatic: setRefreshing(true/false).