이 예제는 사용자가 Android 액티비티(Activity)를 종료하려는 의도가 있는지 확인하는 다이얼로그(Dialog)를 표시하는 방법을 보여줍니다. 뒤로 가기 버튼을 눌렀을 때 실수로 앱이 종료되는 것을 방지하고 싶다면, onBackPressed() 메서드를 오버라이드하여 AlertDialog로 사용자에게 확인을 요청할 수 있습니다.
1단계 — 새 프로젝트 생성
Android Studio에서 File → New Project를 선택한 후, 새 프로젝트를 만들기 위해 필요한 모든 세부 정보를 입력합니다.
2단계 — 레이아웃 파일 작성
res/layout/activity_main.xml에 아래 코드를 추가합니다.
<?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:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Dialog to confirm that the user wishes to exit an
Android Activity"
android:textAlignment="center"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>3단계 — MainActivity에 다이얼로그 로직 구현
src/MainActivity.java에 아래 코드를 추가합니다. 핵심은 onBackPressed() 메서드 안에서 AlertDialog를 생성하고, '예' 버튼 클릭 시 finish()를 호출해 액티비티를 종료하는 것입니다.
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onBackPressed() {
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing Activity").setMessage("Are you sure you want to close this activity?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
Toast.makeText(MainActivity.this, "Activity closed", Toast.LENGTH_SHORT).show();
}
}).setNegativeButton("No", null).show();
}
}코드 설명
- setIcon(): 다이얼로그에 표시될 경고 아이콘을 설정합니다.
- setTitle() / setMessage(): 다이얼로그의 제목과 안내 메시지를 지정합니다.
- setPositiveButton("Yes"): '예'를 누르면 finish()로 액티비티를 종료하고 Toast 메시지를 표시합니다.
- setNegativeButton("No", null): '아니오'를 누르면 리스너가 없으므로 다이얼로그만 닫히고 액티비티는 유지됩니다.
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 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바에서 Run(실행) 아이콘을 클릭하세요. 옵션에서 모바일 기기를 선택하면 기기에 기본 화면이 표시됩니다.
여기서 뒤로 가기 버튼을 누르면 "Closing Activity" 제목의 확인 다이얼로그가 나타나고, Yes를 선택하면 액티비티가 종료되며 "Activity closed" 토스트 메시지가 표시됩니다.
