본문 바로가기
안드로이드 자바

[Java][Android] check box 란? , 체크박스 빠르게 커스텀하기

by teamnova 2021. 2. 23.

이번 예제에서는 체크박스(checkbox)에 대해서 알아보고 커스텀해보겠습니다.

 

스틱코드라는 플러그인을 이용해서 빠르게 개발을 해볼 건데요

 

custombox 코드

stickode.com/detail.html?no=1879

 

스틱코드

 

stickode.com

위의 포스팅을 즐겨찾기 추가 또는 팔로우하시면 좀 더 빠르게 개발하실 수 있습니다.

 

==========================================================================

체크박스

 

체크박스는 사용자가 세트에서 하나 이상의 옵션을 선택할 때 사용할 수 있습니다.

CheckBox는 "선택됨(checked)"과 "선택되지 않음(unchecked)"으로 구분된 두 가지 상태를 가집니다

유사한 것으로는 RadioButton, Switch 등이 있습니다.

 

체크박스 기본형 (xml)

 <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Check"
        android:id="@+id/checkBox"/>

 

체크박스 클릭 이벤트

 CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox) ;
        checkBox.setOnClickListener(new CheckBox.OnClickListener() {
            @Override
            public void onClick(View v) {
            
            }
        }) ;

 

체크박스 상태 가져오기

 if (checkBox.isChecked()) {
        // TODO : CheckBox is checked.
    } else {
        // TODO : CheckBox is unchecked.
    }

 체크박스 상태 변경하기

 checkBox.setChecked(true) ;
 checkBox.setChecked(false) ;

 

===========================================================================

이번에 개발한 커스텀 체크박스 예제 화면입니다.

 

체크박스 예제 화면

==========================================================================

커스텀 체크박스 만들기

1. 커스텀할 체크박스 이미지를 res-> drawable 안에 넣습니다.

 

2. res-> drawable 안에 Drawable Resource File을 생성 한 후 아래 코드를 작성합니다

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 체크박스 해제 상태 -->
    <item android:state_checked="false"
        android:drawable="@drawable/check_inactive"/>
    <!-- 체크박스 선택 상태 -->
    <item android:state_checked="true"
        android:drawable="@drawable/check_active"/>
</selector>

(check_inactive, check_active 를 각 이미지의 이름으로 변경해주세요)

 


*스틱 코드를 이용하면 게시물 즐겨찾기 추가 후 태그를 이용해서 쉽게 사용할 수 있습니다.*

 

3. 화면 레이아웃에 체크박스 background를 자신이 만든 drawable 파일이름으로 변경하면 됩니다.

        <CheckBox
            android:id="@+id/fall_checkbox"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:button="@null"
            android:background="@drawable/custom_checkbox" />

아까 제가 올려놓은 스틱코드를 이용하면 더 빠르게 개발하실 수 있습니다.

 

============================================================================

전체코드

 

커스텀 체크박스 레이아웃 코드입니다. (custom_checkbox.xml)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 체크박스 해제 상태 -->
    <item android:state_checked="false"
        android:drawable="@drawable/check_inactive"/>
    <!-- 체크박스 선택 상태 -->
    <item android:state_checked="true"
        android:drawable="@drawable/check_active"/>
</selector>

 

커스텀 체크박스 예제 화면 레이아웃 코드입니다. (activity_main.xml)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="좋아하는 계절을 고르시오"
        android:textSize="20dp"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginLeft="160dp"
        android:layout_marginTop="5dp">

        <CheckBox
            android:id="@+id/spring_checkbox"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:button="@null"
            android:background="@drawable/custom_checkbox" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:text="봄"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginLeft="160dp"
        android:layout_marginTop="5dp">

        <CheckBox
            android:id="@+id/summer_checkbox"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:button="@null"
            android:background="@drawable/custom_checkbox" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:text="여름"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginLeft="160dp"
        android:layout_marginTop="5dp">

        <CheckBox
            android:id="@+id/fall_checkbox"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:button="@null"
            android:background="@drawable/custom_checkbox" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:text="가을"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginLeft="160dp"
        android:layout_marginTop="5dp">

        <CheckBox
            android:id="@+id/winter_checkbox"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:button="@null"
            android:background="@drawable/custom_checkbox" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:text="겨울"/>
    </LinearLayout>

    <TextView
        android:id="@+id/resultTV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="결과"
        android:layout_gravity="center"
        android:layout_marginTop="50dp"
        android:textSize="20dp"/>

</LinearLayout>

 

커스텀 체크박스 예제 자바 코드입니다. (MainActivity.xml)

package com.example.stickcode_checkbox;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {

    CheckBox spring_checkbox;
    CheckBox summer_checkbox;
    CheckBox fall_checkbox;
    CheckBox winter_checkbox;
    TextView resultTV;

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

        spring_checkbox = (CheckBox)findViewById(R.id.spring_checkbox);
        summer_checkbox = (CheckBox)findViewById(R.id.summer_checkbox);
        fall_checkbox = (CheckBox)findViewById(R.id.fall_checkbox);
        winter_checkbox = (CheckBox)findViewById(R.id.winter_checkbox);
        resultTV = (TextView)findViewById(R.id.resultTV);

        spring_checkbox.setOnCheckedChangeListener(this);
        summer_checkbox.setOnCheckedChangeListener(this);
        fall_checkbox.setOnCheckedChangeListener(this);
        winter_checkbox.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        String result = "";

        if(spring_checkbox.isChecked()) result += "봄 ";
        if(summer_checkbox.isChecked()) result += "여름 ";
        if(fall_checkbox.isChecked()) result += "가을 ";
        if(winter_checkbox.isChecked()) result += "겨울 ";

        resultTV.setText("결과 : " + result);
    }
}