개발공부

[Android] AlertDialog 사용법, 백 버튼 이벤트 예제 본문

Android

[Android] AlertDialog 사용법, 백 버튼 이벤트 예제

mscha 2022. 7. 12. 17:48

AlertDialog

AlertDialog는 팝업창을 띄워 사용자에게 선택창을 보여주고 선택을 하게 할 수 있습니다.

이번에는 AlertDialog를 사용해 사용자가 기계의 뒤로가기(back) 버튼을 눌렀을 때,

종료를 할 것인지 하지 않을 것인지를 선택하는 예제코드를 보여드리겠습니다.

 

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
			// ...
    }
    
    // 백 버튼누를때 실행되는 함수
    @Override
    public void onBackPressed() {
    	// AlertDialog 객체 생성
        AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
        
        // 제목 설정
        alert.setTitle("앱 종료!");
        
        // 긍정버튼
        // ("메세지", 리스너)
        alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        	// 긍정 버튼을 눌렀을 때의 함수
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                finish();
            }
        });
        // 부정버튼을 눌렀을때
        // 리스너 메소드는 필요 없으니 null로 설정
        alert.setNegativeButton("No", null);
		
        // alert를 보여준다.
        alert.show();
    }
}

추가기능

타이틀 아래 메시지 설정

alert.setMessage("메시지");

 

알러트 다이얼로그의 버튼을 누르지 않으면 넘어가지 않도록 하는 방법

default는 true

alert.setCancelable(false);