Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드에서 체크박스(CheckBox)를 사용하는 방법 – 단계별 예제

이 튜토리얼에서는 안드로이드 앱에서 체크박스(CheckBox)를 사용하는 방법을 실제 예제를 통해 알아봅니다. 피자, 커피, 버거 세 가지 메뉴를 체크박스로 선택하고, 주문 버튼을 누르면 선택한 항목과 총 금액을 토스트(Toast)로 표시하는 간단한 주문 화면을 만들어 보겠습니다.

1단계 – 새 프로젝트 생성

Android Studio에서 File ⇒ New Project를 선택한 후, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.

2단계 – 레이아웃 XML 작성

res/layout/activity_main.xml 파일에 다음 코드를 추가합니다. 세 개의 체크박스(피자, 커피, 버거)와 하나의 주문 버튼을 ConstraintLayout 안에 배치합니다.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
   xmlns:android="https://schemas.android.com/apk/res/android"
   xmlns:app="https://schemas.android.com/apk/res-auto"
   xmlns:tools="https://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="MainActivity">
   <CheckBox
      android:id="@+id/checkBox"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginLeft="144dp"
      android:layout_marginTop="68dp"
      android:text="Pizza"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent" />
   <CheckBox
      android:id="@+id/checkBox2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginLeft="144dp"
      android:layout_marginTop="28dp"
      android:text="Coffee"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/checkBox" />
   <CheckBox
      android:id="@+id/checkBox3"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginLeft="144dp"
      android:layout_marginTop="28dp"
      android:text="Burger"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/checkBox2" />
   <Button
      android:id="@+id/button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginLeft="144dp"
      android:layout_marginTop="184dp"
      android:text="Order"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/checkBox3" />
</android.support.constraint.ConstraintLayout>

3단계 – MainActivity.java 작성

src/MainActivity.java에 다음 코드를 추가합니다. 버튼 클릭 시 각 체크박스의 isChecked() 메서드로 선택 여부를 확인하고, 선택된 항목의 가격을 합산한 뒤 StringBuilder로 결과 문자열을 만들어 Toast로 화면에 표시합니다.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
   CheckBox pizza,coffee,burger;
   Button buttonOrder;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      pizza = findViewById(R.id.checkBox);
      coffee = findViewById(R.id.checkBox2);
      burger = findViewById(R.id.checkBox3);
      buttonOrder = findViewById(R.id.button);
      buttonOrder.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            int totalAmount = 0;
            StringBuilder result = new StringBuilder();
            result.append("Selected Items");
            if (pizza.isChecked()) {
               result.append("\nPizza 100Rs");
               totalAmount += 100;
            }
            if (coffee.isChecked()) {
               result.append("\nCoffe 50Rs");
               totalAmount += 50;
            }
            if (burger.isChecked()) {
               result.append("\nBurger 120Rs");
               totalAmount += 120;
            }
            result.append("\nTotal: " + totalAmount + "Rs");
            Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_SHORT).show();
         }
      });
   }
}

4단계 – AndroidManifest.xml 설정

androidManifest.xml에 다음 코드를 추가합니다. MainActivity가 앱의 시작(Launcher) 액티비티로 등록되어 있는지 확인하세요.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하세요. 기기 목록에서 자신의 모바일 기기를 선택하면, 해당 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

안드로이드에서 체크박스(CheckBox)를 사용하는 방법 – 단계별 예제

안드로이드에서 체크박스(CheckBox)를 사용하는 방법 – 단계별 예제