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

안드로이드 라디오 버튼(RadioButton) 사용법 – 단계별 예제 가이드

이 튜토리얼에서는 안드로이드 앱에서 라디오 버튼(RadioButton)을 사용하는 방법을 단계별로 살펴봅니다. 라디오 버튼은 여러 선택지 중 오직 하나만 선택할 수 있도록 할 때 유용하며, 반드시 RadioGroup으로 묶어서 사용해야 그룹 내에서 하나의 항목만 선택되도록 동작합니다.

여기서는 성별(남성/여성)을 선택하는 간단한 예제를 만들고, 버튼을 누르면 선택된 항목을 토스트(Toast) 메시지로 표시해 보겠습니다.

1단계: 새 프로젝트 생성

Android Studio를 실행한 후 File ⇒ New Project 메뉴로 이동하여 새 프로젝트 생성에 필요한 모든 정보를 입력하고 프로젝트를 만듭니다.

2단계: 레이아웃 XML 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 두 개의 라디오 버튼을 하나의 RadioGroup으로 감싸고, 하단에는 결과를 표시할 버튼을 배치했습니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <RadioGroup
        android:id="@+id/radioGender"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true">

        <RadioButton
            android:id="@+id/radioMale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radioMale"
            android:checked="true" />

        <RadioButton
            android:id="@+id/radioFemale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radioFemale" />
    </RadioGroup>

    <Button
        android:id="@+id/btnDisplay"
        android:layout_below="@id/radioGender"
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btnDisplay" />

</RelativeLayout>

위 코드에서 android:checked="true" 속성 덕분에 '남성(Male)' 항목이 기본적으로 선택된 상태로 시작합니다.

3단계: MainActivity 자바 코드 작성

src/MainActivity.java 파일에 다음 코드를 추가합니다. 버튼 클릭 시 getCheckedRadioButtonId() 메서드로 현재 선택된 라디오 버튼의 ID를 가져오고, 해당 버튼의 텍스트를 토스트로 출력합니다.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    RadioGroup radioGroup;
    RadioButton radioButton;
    Button button;

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

    private void addListenerButton() {
        radioGroup = findViewById(R.id.radioGender);
        button = findViewById(R.id.btnDisplay);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int selectedID = radioGroup.getCheckedRadioButtonId();
                radioButton = findViewById(selectedID);
                Toast.makeText(MainActivity.this,
                        radioButton.getText(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

4단계: 문자열 리소스(strings.xml) 추가

res/values/strings.xml 파일을 열고 아래 코드를 추가합니다. UI 텍스트를 리소스로 분리하면 다국어 지원과 유지보수에 유리합니다.

<resources>
    <string name="app_name">Sample</string>
    <string name="radioMale">Male</string>
    <string name="radioFemale">Female</string>
    <string name="btnDisplay">Display</string>
</resources>

5단계: AndroidManifest.xml 확인

androidManifest.xml 파일에 아래 코드가 올바르게 등록되어 있는지 확인합니다. 메인 액티비티가 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 아이콘을 클릭하세요. 실행 기기 목록에서 모바일 기기를 선택하면, 기기 화면에 아래와 같이 라디오 버튼과 버튼이 표시됩니다.

안드로이드 라디오 버튼(RadioButton) 사용법 – 단계별 예제 가이드

버튼을 누르면 현재 선택된 성별 항목이 토스트 메시지로 잠깐 나타나는 것을 확인할 수 있습니다. 이처럼 RadioGroup과 RadioButton을 조합하면 설문조사, 설정 화면, 결제 수단 선택처럼 '단일 선택'이 필요한 다양한 UI를 손쉽게 구현할 수 있습니다.