Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드 당겨서 새로고침(Pull-to-Refresh) 구현 방법 완벽 가이드


안드로이드 Pull-to-Refresh(당겨서 새로고침)란?

예제를 시작하기 전에, 안드로이드의 '당겨서 새로고침(Pull to Refresh)' 레이아웃이 무엇인지 먼저 알아보겠습니다. 안드로이드에서는 이 기능을 스와이프 새로고침(Swipe-to-Refresh)이라고도 부릅니다. 화면을 위에서 아래로 끌어당기면 setOnRefreshListener에 등록된 동작이 실행되는 방식으로, 주로 목록이나 콘텐츠를 최신 상태로 갱신할 때 사용됩니다.

이 글에서는 안드로이드에서 당겨서 새로고침 기능을 단계별로 구현하는 방법을 소개합니다.

1단계: 새 프로젝트 생성

안드로이드 스튜디오에서 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을 부모 레이아웃으로 지정했습니다. 사용자가 이 레이아웃을 위에서 아래로 스와이프하면 그 안의 자식 뷰(TextView)가 새로 고쳐집니다.

참고: 최신 안드로이드 스튜디오 환경에서는 구버전 서포트 라이브러리(android.support.v4) 대신 AndroidX의 androidx.swiperefreshlayout.widget.SwipeRefreshLayout을 사용하는 것이 권장됩니다. Gradle에 androidx.swiperefreshlayout:swiperefreshlayout:1.1.0 의존성을 추가하면 됩니다.

3단계: MainActivity 작성

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() 메서드가 호출되며, 여기서는 스와이프 횟수를 세어 TextView의 텍스트를 갱신하도록 구현했습니다. 핵심 로직은 아래와 같습니다.

swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
    @Override
    public void onRefresh() {
        i++;
        textView.setText("Tutorialspoint.com "+i);
        swipeRefresh.setRefreshing(false);
    }
});

setRefreshing(false)를 호출하면 새로고침이 완료된 후 로딩 인디케이터(회전 애니메이션)가 사라집니다. 실제 프로젝트에서는 이 위치에서 네트워크 요청이나 데이터 갱신 작업을 수행하고, 작업이 끝난 뒤 인디케이터를 종료하는 패턴이 일반적입니다.

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. 안드로이드 스튜디오에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하세요. 기기 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 초기 화면이 표시됩니다.

안드로이드 당겨서 새로고침(Pull-to-Refresh) 구현 방법 완벽 가이드

위 결과는 초기 화면입니다. 이제 화면을 위에서 아래로 스와이프하면 아래와 같이 TextView의 텍스트가 갱신되는 것을 확인할 수 있습니다.

안드로이드 당겨서 새로고침(Pull-to-Refresh) 구현 방법 완벽 가이드


안드로이드 당겨서 새로고침(Pull-to-Refresh) 구현 방법 완벽 가이드