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

안드로이드에서 다이얼로그 바깥쪽을 클릭하면 닫히도록 구현하는 방법

개요

이 글에서는 안드로이드 앱에서 다이얼로그(Dialog) 바깥 영역을 터치했을 때 자동으로 닫히도록 구현하는 방법을 단계별로 살펴봅니다. 핵심은 AlertDialogsetCanceledOnTouchOutside(true) 메서드 한 줄이며, 이를 통해 사용자가 다이얼로그 외부를 클릭하면 별도의 버튼 조작 없이 다이얼로그가 취소됩니다.

1단계 — 새 프로젝트 생성

Android Studio를 실행하고 File → New Project로 이동한 뒤, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.

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

res/layout/activity_main.xml에 아래 코드를 추가합니다. 화면 중앙에 'Click'이라는 텍스트를 배치하는 간단한 구조입니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android"
    android:layout_width = "match_parent"
    android:gravity = "center"
    android:layout_height = "match_parent">
    <TextView
        android:id = "@+id/click"
        android:layout_width = "wrap_content"
        android:textSize = "30sp"
        android:layout_height = "wrap_content"
        android:text = "Click"/>
</LinearLayout>

3단계 — MainActivity 작성

src/MainActivity.java에 아래 코드를 추가합니다. TextView를 클릭하면 알럿 다이얼로그가 표시되고, alert.setCanceledOnTouchOutside(true); 구문 덕분에 다이얼로그 바깥쪽을 터치하면 자동으로 닫힙니다.

import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    TextView text;
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = findViewById(R.id.click);
        text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAlertBox();
            }
        });
    }
    private void showAlertBox() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
        alertDialog.setTitle("AlertDialog");
        alertDialog.setMessage("Do you wanna close the dialog box? ");
        alertDialog.setPositiveButton("yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this,"you clicked on yes button",Toast.LENGTH_LONG).show();
            }
        });
        alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        AlertDialog alert = alertDialog.create();
        alert.setCanceledOnTouchOutside(true);
        alert.show();
    }
}

참고: 최신 프로젝트(AndroidX 기반)에서는 android.support.v7.app.AlertDialog 대신 androidx.appcompat.app.AlertDialog를 import해야 합니다. 또한 setCanceledOnTouchOutside(false)로 설정하면 반대로 바깥쪽을 눌러도 다이얼로그가 닫히지 않습니다.

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="app.com.sample.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(실행) 아이콘을 클릭합니다. 옵션 목록에서 자신의 모바일 기기를 선택하면, 기본 화면이 표시된 것을 확인할 수 있습니다.

화면 중앙의 'Click' 텍스트를 누르면 알럿 다이얼로그가 나타나고, 다이얼로그 바깥쪽 어디든 터치하면 즉시 닫히는 것을 확인할 수 있습니다. 'yes' 버튼을 누르면 토스트 메시지가 표시됩니다.

안드로이드에서 다이얼로그 바깥쪽을 클릭하면 닫히도록 구현하는 방법

안드로이드에서 다이얼로그 바깥쪽을 클릭하면 닫히도록 구현하는 방법