앱 만들기/안드로이드

체크박스 형 기본 다이얼로그 만들기

나도 처음이야 2022. 7. 19.

https://soo0100.tistory.com/1901

 

리스트형 기본 다이얼로그 만들기

https://soo0100.tistory.com/1900 기본 다이얼로그 박스 만들기 안드로이드 Alert Dialog 라고 불리는 기본 다이얼로그를 만들어 봅니다. 결과는 하기와 같습니다. 1. XML 화면구성으로 버튼을 하나 만듭니다.

soo0100.tistory.com

 

체크형 기본 다이얼로그를 제작해 봅니다.

구성은 지난 시간과 동일하며, 다이얼로그 생성 함수만 제작하면 되겠습니다.

1. 체크박스형 다이얼로그를 생성하는 함수를 만들어줍니다.

final CharSequence[] items ={"제주", "프랑크푸르트" , "파리"};

public void AlertDialogCheckBoxType(View view){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("목적지를 선택하세요");
    builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener(){
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            Toast.makeText(getApplicationContext(), items[i], Toast.LENGTH_LONG).show();
        }
    });
    builder.show();
}

체크박스 타입을 사용하기 위해서는

builder.setSingChoiceItems() 함수를 사용하는 것이 키 포인트가 되겠습니다.

두번째 인자 값은 리스트의 인덱스를 나타냅니다. -1 로 설정하면 선택된 값이 없이 나옵니다.

2. 화면구성 XML버튼의 Onclick 속성에 해당 함수를 연결해 줍니다.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:onClick="AlertDialogCheckBoxType"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="AlertDialogCheckBoxType"
        android:text="Alert Dialog"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

해당 코드에 조금만 더 수정을 하면,

다중체크 박스를 만들 수도 있습니다. 코드는 하기 처럼 구현 하면 되겠습니다.

- setMultiChoiceItems() 함수를 사용했습니다. 두번째 인자는 역시 선택 유무를 뜻합니다.

- 클릭 리스너에서 중복체크한 항목을 arraylist 에 저장하는 하는 항목이 키 포인트가 되겠습니다.

- 해당 arraylist 에서 값을 빼와서 정보를 별도로 저장 혹은 가공하면 됩니다.

- 해당 예제에서는 두개의 버튼도 달아 보았습니다.

ArrayList array = new ArrayList();
public void AlertDialogCheckBoxType(View view){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("목적지를 선택하세요");
    builder.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int index, boolean isChecked) {
            if (isChecked) {
                // If the user checked the item, add it to the selected items
                array.add(index);
            } else if (array.contains(index)) {
                // Else, if the item is already in the array, remove it
                array.remove(index);
            }
        }
    });

    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            // User clicked OK, so save the selectedItems results somewhere
            // or return them to the component that opened the dialog

        }
    }).setNegativeButton("NO", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {

                }
            });
    builder.show();
}

결과는 하기와 같습니다.

 

싱글 및 멀티 체크박스에 대한 개발자 페이지 내용입니다

참고 드립니다. 감사합니다.

 

반응형

댓글