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

[Java][Android] Alert Dialog 다이얼로그 띄우고 Back 버튼 뒤로가기 막기

by teamnova 2022. 9. 28.

안녕하세요.

오늘은 안드로이드에서 간단한 다이얼로그를 띄워보고 뒤로가기 버튼을 막는 것까지 해보겠습니다.

 

먼저 xml 파일입니다.

<!-- dialog_test.xml -->

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

    <Button
        android:id="@+id/dialogBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="#9C27B0"
        android:onClick="DialogClick"
        android:layout_gravity="center"
        android:text="다이얼로그 버튼" />

</LinearLayout>

버튼을 클릭하면 다이얼로그를 띄울 수 있도록 버튼을 만들었습니다.

 

다음으로 자바 파일입니다.

// DialogTest.java

public class DialogTest extends AppCompatActivity {
    Button button;

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

        button = findViewById(R.id.dialogBtn);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { // 버튼 클릭 시
                AlertDialog.Builder builder = new AlertDialog.Builder(DialogTest.this); // 다이얼로그 생성 및 출력
                builder.setTitle("다이얼로그 테스트") // 다이얼로그 제목
                        .setMessage("테스트입니다.") // 다이얼로그 메시지
                        .setPositiveButton("예", new DialogInterface.OnClickListener(){ // '예' 버튼 
                            public void onClick(DialogInterface dialog, int whichButton){ // 클릭 시
                                button.setText(" '예' 버튼이 클릭됨."); // 버튼 텍스트 변경
                            }
                        })
                        .setNegativeButton("취소", new DialogInterface.OnClickListener(){ // '취소' 버튼
                            public void onClick(DialogInterface dialog, int whichButton){ // 클릭 시
                                dialog.cancel(); // 다이얼로그가 닫힘 (취소됨)
                            }
                        });
                AlertDialog dialog = builder.create();
                dialog.show();
            }
        });
    }
}

실행화면 입니다.

 

보시는 것과 같이 다이얼로그가 작동이 됩니다.

하지만 다이얼로그 외의 화면과 에뮬레이터의 뒤로가기 버튼을 클릭 시 다이얼로그가 사라지게 되는데요.

다이얼로그 부분의 코드를 아래와 같이 수정해줍니다.

AlertDialog.Builder builder = new AlertDialog.Builder(DialogTest.this); // 다이얼로그 생성 및 출력
builder.setTitle("다이얼로그 테스트") // 다이얼로그 제목
        .setMessage("테스트입니다.") // 다이얼로그 메시지
        .setCancelable(false) // 추가된 부분
        .setPositiveButton("예", new DialogInterface.OnClickListener(){ // '예' 버튼
            public void onClick(DialogInterface dialog, int whichButton){ // 클릭 시
                button.setText(" '예' 버튼이 클릭됨."); // 버튼 텍스트 변경
            }
        })
        .setNegativeButton("취소", new DialogInterface.OnClickListener(){ // '취소' 버튼
            public void onClick(DialogInterface dialog, int whichButton){ // 클릭 시
                dialog.cancel(); // 다이얼로그가 닫힘 (취소됨)
            }
        });
AlertDialog dialog = builder.create();
dialog.show();

 

반드시 확인 버튼 혹은 취소 버튼 둘 중 하나를 클릭해야 다이얼로그가 종료될 수 있도록 뒤로가기를 막는 방법입니다.

보시다시피 다이얼로그를 세팅할 때에 .setCancelable(false)를 추가해줍니다.

실행화면 입니다.

 

보시는 것과 같이

이제 다이얼로그 화면 외의 바탕화면을 클릭하거나, 뒤로가기 버튼을 눌러도 다이얼로그가 종료되지 않고,

다이얼로그의 버튼을 클릭해야만 다이얼로그가 종료됩니다.

 

궁금한 점은 언제든 댓글로 남겨주세요.

감사합니다.