본문 바로가기
안드로이드 자바

[Java][Android] Dialog 외부 터치 시 닫히지 않게 하기

by teamnova 2025. 4. 29.
728x90

안녕하세요.

오늘은 Dialog 외부 터치 시 닫히지 않게 해보도록 하겠습니다.

 

안드로이드의 Dialog는 기본적으로 외부를 터치하면 자동으로 닫히는 동작을 합니다.
그러나 중요한 알림이나 경고 문구, 또는 사용자의 명확한 동의를 받아야 하는 안내사항의 경우, 반드시 버튼을 클릭해야 넘어가도록 구현할 필요가 있습니다.
이럴 때 외부 터치로 다이얼로그가 닫히지 않게 설정하면, 보다 안전하고 명확한 사용자 경험을 제공할 수 있습니다.

 

우선 전체 코드입니다.

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:gravity="center"
  android:orientation="vertical">

  <Button
    android:id="@+id/btn_show_dialog"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="다이얼로그" />

</LinearLayout>

 

MainActivity.java

public class MainActivity extends AppCompatActivity {

  private Button btnShowDialog;
  private AlertDialog currentDialog;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnShowDialog = findViewById(R.id.btn_show_dialog);

    btnShowDialog.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        showCustomDialog();
      }
    });
  }

  private void showCustomDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("주의")
        .setMessage("버튼을 눌러야만 닫힙니다.")
        .setPositiveButton("확인", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialogInterface, int i) {
            // 확인 버튼 눌렀을 때
          }
        });

    currentDialog = builder.create();
    currentDialog.setCanceledOnTouchOutside(false); // 외부 터치로 닫히지 않게 설정
    currentDialog.show();
    
  }
}

 

이렇게 setCanceledOnTouchOutside(false); 설정을 통해 외부 터치 시 닫히지 않게 구현할 수 있습니다.

 

이것을 응용해서 다양한 동작들을 만들어보시길 바랍니다.

 

시연 영상입니다.