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

안드로이드에서 대화상자 외부를 클릭해 닫는 방법 (AlertDialog 예제)

이 튜토리얼은 안드로이드에서 대화상자(AlertDialog) 바깥 영역을 클릭했을 때 대화상자를 닫거나 닫히지 않도록 제어하는 방법을 실제 예제와 함께 단계별로 설명합니다.

1단계: 새 프로젝트 생성

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

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

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<?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>

위 코드에서는 화면 중앙에 클릭 가능한 TextView 하나를 배치했습니다.

3단계: MainActivity 구현

src/MainActivity.java 파일에 다음 코드를 추가합니다.

package com.example.myapplication;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
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
   public 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) {
            showAlertDialog();
         }
      });
   }
   private void showAlertDialog() {
      AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
      alertDialog.setTitle("AlertDialog");
      alertDialog.setMessage("Sairamkrishna Mammahe do you wanna close it or not?");
      alertDialog.setIcon(R.drawable.logo);
      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(false);
      alert.show();
   }
}

핵심 포인트: setCanceledOnTouchOutside() 메서드

위 코드의 핵심은 alert.setCanceledOnTouchOutside(false) 부분입니다. 이 값을 false로 설정하면 대화상자 바깥을 클릭해도 닫히지 않습니다. 반대로 true(기본값)로 설정하면 바깥 영역을 터치하는 것만으로 대화상자가 자동으로 닫힙니다. 따라서 외부 클릭으로 대화상자를 닫고 싶다면 이 값을 true로 지정하거나 해당 코드를 삭제하면 됩니다.

실행 결과 확인

실제 안드로이드 기기를 컴퓨터에 연결한 상태에서, Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭합니다. 실행 옵션에서 연결된 모바일 기기를 선택하면 앱이 설치되고 다음과 같은 기본 화면이 표시됩니다.

안드로이드에서 대화상자 외부를 클릭해 닫는 방법 (AlertDialog 예제)

이제 화면의 TextView를 클릭하면 다음과 같이 Alert Dialog가 나타나는 것을 확인할 수 있습니다.

안드로이드에서 대화상자 외부를 클릭해 닫는 방법 (AlertDialog 예제)