본문 바로가기

안드로이드 개발/개발팁

안드로이드 알림창 띄우기

[Android] 알림창 띄우기 AlertDialog 




안드로이드의 대표적인 알림창인 AlertDialog만 사용해도 사용자 인터페이스에서 필요한 대부분의 대화 상자를 구현할 수 있다. AlertDialog를 생성하기 위해서 먼저 AlertDialog.Builder 객체를 생성하고 이 객체의 메소드들을 호출해서 속성을 지정하고 생성한다.



1. 메세지와 확인/취소 버튼이 있는 알림창







AlertDialog.Builder builder = new AlertDialog.Builder(this);     // 여기서 this는 Activity의 this


// 여기서 부터는 알림창의 속성 설정

builder.setTitle("종료 확인 대화 상자")        // 제목 설정

.setMessage("앱을 종료 하시 겠습니까?")        // 메세지 설정

.setCancelable(false)        // 뒤로 버튼 클릭시 취소 가능 설정

.setPositiveButton("확인", new DialogInterface.OnClickListener(){       

 // 확인 버튼 클릭시 설정

public void onClick(DialogInterface dialog, int whichButton){

finish();   


}

})

.setNegativeButton("취소", new DialogInterface.OnClickListener(){      

     // 취소 버튼 클릭시 설정

public void onClick(DialogInterface dialog, int whichButton){

dialog.cancel();

}

});


AlertDialog dialog = builder.create();    // 알림창 객체 생성

dialog.show();    // 알림창 띄우기






2. 선택 목록을 사용하는 알림창








final CharSequence[] items = {"Red", "Green", "Blue"};


AlertDialog.Builder builder = new AlertDialog.Builder(this);     // 여기서 this는 Activity의 this


// 여기서 부터는 알림창의 속성 설정

builder.setTitle("색상을 선택하세요")        // 제목 설정

.setItems(items, new DialogInterface.OnClickListener(){    // 목록 클릭시 설정

public void onClick(DialogInterface dialog, int index){

Toast.makeText(getApplicationContext(), items[index], Toast.LENGTH_SHORT).show();

}

});


AlertDialog dialog = builder.create();    // 알림창 객체 생성

dialog.show();    // 알림창 띄우기





setItems() 메소드는 표시할 항목의 배열과 OnClickListener를 매개 변수로 받는다. OnClickListener는 사용자가 항목을 선택하는 경우에 실행되는 동작을 정의한다.





3. 선택 목록 알림창에 라디오버튼 추가하기









final CharSequence[] items = {"Red", "Green", "Blue"};


AlertDialog.Builder builder = new AlertDialog.Builder(this);     // 여기서 this는 Activity의 this


// 여기서 부터는 알림창의 속성 설정

builder.setTitle("색상을 선택하세요")        // 제목 설정

.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener(){   

 // 목록 클릭시 설정

public void onClick(DialogInterface dialog, int index){

Toast.makeText(getApplicationContext(), items[index], Toast.LENGTH_SHORT).show();

}

});


AlertDialog dialog = builder.create();    // 알림창 객체 생성

dialog.show();    // 알림창 띄우기



setItems()를 setSingleChoiceItems()로 바꿔주면 된다. 그러면 목록 옆에 라디오 버튼이 추가된다. 만약 다중 선택을 가능하게 하고 싶으면 setMultiChoiceItems()를 사용하면 된다. 아 그리고 ! 빨간색으로 표시한 -1 (setSingleChoiceItems()의 두번째 매개변수)는 초기에 선택될 항목을 나타내는 정수로서 -1은 아직 선택된 항목이 없음을 나타낸다.


※ 참고로 AlertDialog는 액티비티의 생명주기에 맞춰 관리가 되므로 사용자가 액티비티를 떠나거나 잠시 중지하는 경우, 선택되었던 항목들을 보관하려면 액티비티 생명주기 메소드를 통해 설정을 보관하고 복원하는 작업을 해야한다. 영구적으로 선택을 저장하려면 데이터 스토리지 기법을 사용해야한다.







참고 블로그 : http://ccdev.tistory.com/12