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

Kotlin으로 안드로이드 스와이프 새로고침(SwipeRefreshLayout) 레이아웃 구현하기

이 튜토리얼에서는 Kotlin을 사용해 안드로이드 앱에 스와이프 새로고침(SwipeRefreshLayout) 기능을 구현하는 방법을 단계별로 알아봅니다. 스와이프 새로고침은 사용자가 화면을 아래로 당겨 데이터를 갱신할 수 있게 해주는 머티리얼 디자인 패턴으로, 뉴스 앱이나 SNS 피드 등에서 널리 사용됩니다.

1단계: 새 프로젝트 생성

Android Studio를 실행하고 File → New Project 메뉴로 이동한 후, 빈 프로젝트(Empty Activity)를 선택하고 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다. 언어는 Kotlin으로 설정합니다.

2단계: 레이아웃 파일 작성 (activity_main.xml)

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. SwipeRefreshLayout 안에 TextView를 배치하여, 스와이프할 때마다 숫자가 증가하는 화면을 만듭니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/swipe"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Swipe to Reload"
            android:textColor="@android:color/background_dark"
            android:textSize="24sp"
            android:textStyle="bold" />

    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

</RelativeLayout>

3단계: MainActivity.kt 작성

src/MainActivity.kt 파일에 다음 코드를 추가합니다. setOnRefreshListener를 통해 스와이프 이벤트를 감지하고, 스와이프가 발생하면 카운터 값을 증가시킨 뒤 일정 시간 후 로딩 인디케이터를 종료합니다.

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.TextView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout

class MainActivity : AppCompatActivity() {

    lateinit var swipeRefreshLayout: SwipeRefreshLayout
    lateinit var textView: TextView
    var number: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"

        swipeRefreshLayout = findViewById(R.id.swipe)
        textView = findViewById(R.id.textView)

        swipeRefreshLayout.setOnRefreshListener {
            number++
            textView.text = " Total number = $number"
            Handler(Looper.getMainLooper()).postDelayed({
                swipeRefreshLayout.isRefreshing = false
            }, 4000)
        }
    }
}

참고: 예제 코드의 Handler()는 현재 deprecated되었으므로, 위 코드처럼 Handler(Looper.getMainLooper()) 형태로 작성하는 것이 좋습니다. 실제 앱에서는 이 지연 시간 부분에 서버에서 최신 데이터를 가져오는 네트워크 요청 로직을 넣으면 됩니다.

4단계: AndroidManifest.xml 확인

androidManifest.xml 파일이 아래와 같이 올바르게 설정되어 있는지 확인합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.q11">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 버튼을 클릭하세요. 실행 옵션 목록에서 연결된 모바일 기기를 선택하면, 해당 기본 화면이 기기에 표시됩니다.

화면에서 아래로 손가락을 당기면 원형 로딩 인디케이터가 나타나며, 약 4초 후 새로고침이 완료되면서 화면의 숫자가 하나씩 증가하는 것을 확인할 수 있습니다.

이렇게 SwipeRefreshLayout을 활용하면 사용자에게 친숙한 방식으로 데이터를 자연스럽게 갱신하는 UX를 손쉽게 구현할 수 있습니다. RecyclerView나 ListView와 함께 사용하면 더욱 실용적인 피드 화면을 만들 수 있습니다.