Android
Android Studio - AlertDialog 사용법
Cong_S
2022. 7. 12. 17:57
AlertDialog 란, 우리가 스마트폰을 사용하면서 수없이 봐왔던 팝업창 혹은 경고창과 같다.
가장 흔한 예시로 백버튼을 눌러 앱을 나가려할 때에 정말 종료하시겠습니까와 같은
메세지를 담고 있는 팝업창이 있다.
사용법을 알아보자.
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("앱을 종료하시겠습니까?");
alert.setPositiveButton("네", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
alert.setNegativeButton("아니오", null);
alert.show();
큰 흐름은 다음과 같다.
Alertddialog.Builder 로 새로운 Alertddialog 객체를 생성한다.
그 후, 제목과 버튼 등 팝업창에 들어갈 요소를 제작한다.
마지막으로 alert.show(); 로 팝업창을 출력한다.
아래는 기계의 백버튼을 눌렀을 때, 바로 종료하지않고 한번 더 물어본 후 종료하는 코드이다.
@Override
public void onBackPressed() {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("앱을 종료하시겠습니까?");
alert.setPositiveButton("네", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
alert.setNegativeButton("아니오", null);
alert.show();
}
1. onBackPressd() 로 기계의 백버튼을 눌렀을 때 작동하는 함수를 오버라이딩 해온다.
2. AlertDialog 를 설계한다.
3. 네를 눌렀을 땐 finish 메소드로 앱이 종료되게 하였다.
4. 아니오를 눌렀을 땐 아무 일도 일어나지 않도록 하였다.
아래는 실제 팝업 화면이다.