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

안드로이드 액티비티에서 뒤로 가기 버튼 처리하는 방법

이 튜토리얼에서는 안드로이드 액티비티(Activity)에서 뒤로 가기 버튼 동작을 처리하는 방법을 단계별로 알아봅니다. 화면에 배치된 버튼을 눌러 현재 액티비티를 종료하는 예제와 함께, 시스템 뒤로 가기 버튼의 기본 동작을 제어하는 onBackPressed() 메서드 활용법까지 다룹니다.

1단계: 새 프로젝트 생성

Android Studio를 실행한 후 File → New Project 메뉴로 이동하여 새 프로젝트를 생성합니다. 프로젝트 생성에 필요한 모든 세부 정보(프로젝트 이름, 패키지명, 최소 SDK 버전 등)를 입력합니다.

2단계: 레이아웃 파일 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 중앙에 텍스트뷰와 버튼이 배치된 간단한 상대 레이아웃(RelativeLayout) 구성입니다.

<?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:gravity = "center"
    android:layout_height = "match_parent"
    tools:context = ".MainActivity">
    <TextView
        android:text= "My Activity"
        android:textSize = "30sp"
        android:layout_width = "match_parent"
        android:layout_height = "match_parent"
        android:layout_marginVertical="25sp"
        android:layout_margin="23dp"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Back to close the activity"
        android:id="@+id/button"
        android:layout_centerVertical="true"
        android:layout_margin="23dp"/>
</RelativeLayout>

3단계: 메인 액티비티 코드 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다. 버튼에 클릭 리스너를 등록하고, 클릭 시 finish() 메서드를 호출하여 현재 액티비티를 종료합니다.

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
    Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
}

4단계: 매니페스트 파일 설정

androidManifest.xml 파일에 아래 코드를 추가하여 메인 액티비티를 등록합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <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 아이콘을 클릭하세요. 옵션 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

안드로이드 액티비티에서 뒤로 가기 버튼 처리하는 방법

추가 팁: 시스템 뒤로 가기 버튼 직접 제어하기

화면상의 버튼이 아니라 기기의 물리적 또는 내비게이션 바의 뒤로 가기 버튼 동작을 직접 제어하려면, 액티비티에서 onBackPressed() 메서드를 오버라이드하면 됩니다.

@Override
public void onBackPressed() {
    // 뒤로 가기 버튼 클릭 시 실행할 로직 작성
    // 예: 확인 대화상자 표시, 특정 조건에서만 종료 등
    super.onBackPressed();
}

이 메서드 안에서 원하는 로직을 수행한 뒤 super.onBackPressed()를 호출하면 기본 뒤로 가기 동작이 실행되고, 호출하지 않으면 뒤로 가기 동작을 막을 수도 있습니다. 참고로 Android 13(API 33)부터는 예측형 뒤로 가기(Predictive Back) 기능이 도입되어, 보다 세밀한 제어가 필요하다면 OnBackPressedDispatcher 사용이 권장됩니다.