관리 메뉴

나만을 위한 블로그

[Android] 여러 체크박스들을 배열에 담아서 클릭 리스너 붙이는 법 본문

Android

[Android] 여러 체크박스들을 배열에 담아서 클릭 리스너 붙이는 법

참깨빵위에참깨빵 2022. 3. 31. 22:37
728x90
반응형

이번 포스팅에선 여러 체크박스들을 배열에 담아 관리하는 예시 코드와 배열 안의 체크박스들에 클릭 리스너를 붙이고 editText에 TextWatcher를 걸어서 체크박스를 체크할 때 활용하는 코드를 기록한다.

소스코드 복붙하면 바로 작동하는 걸 확인할 수 있다. 이 코드들이 절대 정답이 아니고 작동할 뿐인 코드인 것에 주의하자.

 

<?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"
    tools:context=".MainActivity">

    <CheckBox
        android:id="@+id/first_checkbox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:text="1번 체크박스"/>

    <CheckBox
        android:id="@+id/second_checkbox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="2번 체크박스"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@id/first_checkbox"/>

    <CheckBox
        android:id="@+id/third_checkbox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="3번 체크박스"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/second_checkbox"/>

    <CheckBox
        android:id="@+id/fourth_checkbox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="4번 체크박스"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/third_checkbox"/>

    <CheckBox
        android:id="@+id/fifth_checkbox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="5번 체크박스"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/fourth_checkbox"/>

    <EditText
        android:id="@+id/edittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:enabled="false"
        android:hint="editText"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/fifth_checkbox"/>

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintVertical_bias="1"
        android:enabled="false"
        android:text="버튼"
        app:layout_constraintTop_toBottomOf="@+id/edittext"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.example.testproject.base.BaseActivity;

public class MainActivity extends BaseActivity {

    private CheckBox first;
    private CheckBox second;
    private CheckBox third;
    private CheckBox fourth;
    private CheckBox fifth;
    private EditText edittext;
    private Button button;
    private String data;

    private CheckBox[] checkBoxes;

    private InputMethodManager imm;

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

        imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

        first = findViewById(R.id.first_checkbox);
        second = findViewById(R.id.second_checkbox);
        third = findViewById(R.id.third_checkbox);
        fourth = findViewById(R.id.fourth_checkbox);
        fifth = findViewById(R.id.fifth_checkbox);
        edittext = findViewById(R.id.edittext);
        button = findViewById(R.id.button);
        checkBoxes = new CheckBox[5];

        edittext.addTextChangedListener(new MyTextWatcher(edittext));

        checkBoxes[0] = first;
        checkBoxes[1] = second;
        checkBoxes[2] = third;
        checkBoxes[3] = fourth;
        checkBoxes[4] = fifth;
        for (int i = 0; i < checkBoxes.length; i++) {
            checkBoxes[i].setTag(i);
            checkBoxes[i].setOnClickListener(clickListener);
        }

        button.setOnClickListener(v -> Log.e(TAG, "data : " + data));
    }

    private final View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final int checkedId = view.getId();
            if ((int) view.getTag() != 4) {
                edittext.setText("");
                edittext.clearFocus();
                edittext.setEnabled(false);
                imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);
                button.setEnabled(true);
            } else {
                edittext.setEnabled(true);
                button.setEnabled(false);
            }
            
            for (CheckBox currentCheckBox : checkBoxes) {
                currentCheckBox.setChecked(currentCheckBox.getId() == checkedId);
            }
            
            switch ((int) view.getTag()) {
                case 0 :
                    Toast.makeText(MainActivity.this, "1번 체크박스", Toast.LENGTH_SHORT).show();
                    data = "1번 체크박스";
                    break;

                case 1 :
                    Toast.makeText(MainActivity.this, "2번 체크박스", Toast.LENGTH_SHORT).show();
                    data = "2번 체크박스";
                    break;

                case 2 :
                    Toast.makeText(MainActivity.this, "3번 체크박스", Toast.LENGTH_SHORT).show();
                    data = "3번 체크박스";
                    break;

                case 3 :
                    Toast.makeText(MainActivity.this, "4번 체크박스", Toast.LENGTH_SHORT).show();
                    data = "4번 체크박스";
                    break;

                case 4 :
                    Toast.makeText(MainActivity.this, "5번 체크박스", Toast.LENGTH_SHORT).show();
                    data = "5번 체크박스";
                    break;
            }
        }
    };

    private class MyTextWatcher implements TextWatcher {

        private final EditText editText;

        public MyTextWatcher(EditText editText) {
            this.editText = editText;
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            button.setEnabled(edittext.getText().length() > 1);
            data = edittext.getText().toString();
        }
    }

}

 

위의 소스코드는 아래 작업들을 수행한다.

 

  • 1번 ~ 4번 체크박스 선택 후 버튼을 클릭하면 어떤 체크박스를 골랐는지 로그로 확인할 수 있다. 토스트로도 확인할 수 있다
  • 버튼은 5번 체크박스를 클릭했을 시에는 비활성화상태로 바뀐다. 버튼이 활성화되는 조건은 editText에 2글자 이상 입력하는 것이다
  • 5번 체크박스 클릭 후 다른 체크박스 선택 시 키보드가 올라와있었다면 내려가고 비활성화된 버튼이 다시 활성화된다. editText에 입력했던 내용들도 지워지고 editText가 다시 비활성화된다

 

체크박스를 구분하는 방법은 setTag()를 통해 체크박스마다 정수를 태그로 달아서 구분했다. 정수로 하니까 for문 돌려서 태그를 붙이거나 클릭 리스너를 붙이기도 편하다.

커스텀은 대충 알아서

반응형
Comments