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

Android에서 RadioGroup(라디오 그룹)의 선택된 항목 인덱스 가져오는 방법

개요

이 튜토리얼에서는 Android 앱에서 RadioGroup(라디오 그룹) 안에서 사용자가 어떤 라디오 버튼을 선택했는지 확인하고, 그 결과를 화면에 표시하는 방법을 단계별로 알아봅니다.

핵심은 RadioGroup 클래스가 제공하는 getCheckedRadioButtonId() 메서드입니다. 이 메서드는 현재 선택된 라디오 버튼의 ID를 반환하며, 아무것도 선택되지 않았을 경우 -1을 반환한다는 점을 기억하면 됩니다.

구현 단계

1단계 — Android Studio에서 새 프로젝트 생성

Android Studio를 실행한 뒤 File → New Project 메뉴로 이동하여 새 프로젝트를 생성하고, 필요한 모든 정보를 입력해 프로젝트 설정을 완료합니다.

2단계 — 레이아웃 파일(activity_main.xml) 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 질문을 표시하는 TextView, 두 개의 라디오 버튼(Netflix, Amazon Prime)을 담은 RadioGroup, 그리고 선택 결과를 확인하는 Button으로 구성되어 있습니다.

<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/tvResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="15dp" />
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Which is your most favorite?"
        android:textStyle="bold"
        android:textSize="16sp"
        android:layout_below="@+id/tvResult" />
    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_below="@id/textView"
        android:padding="15dp">
    <RadioButton
        android:id="@+id/rbNetflix"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Netflix"
        android:paddingRight="15dp" />
    <RadioButton
        android:id="@+id/rbAmazonPrime"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Amazon Prime"
        android:paddingRight="15dp" />
    </RadioGroup>
    <Button
        android:id="@+id/btnGetItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Selected Radio Button"
        android:layout_below="@+id/radioGroup" />
</RelativeLayout>

3단계 — MainActivity.java 코드 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다. 버튼 클릭 시 getCheckedRadioButtonId()로 선택된 라디오 버튼의 ID를 가져오고, 값이 -1이 아니면 해당 버튼의 텍스트를 화면에 출력합니다.

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.TextView;
public class MainActivity extends AppCompatActivity {
    TextView textView;
    Button button;
    RadioGroup radioGroup;
    RadioButton selectedRadioButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
        button = findViewById(R.id.btnGetItem);
        radioGroup = findViewById(R.id.radioGroup);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int selectedRadioButtonId = radioGroup.getCheckedRadioButtonId();
                if (selectedRadioButtonId != -1) {
                    selectedRadioButton = findViewById(selectedRadioButtonId);
                    String selectedRbText = selectedRadioButton.getText().toString();
                    textView.setText(selectedRbText + " is Selected");
                } else {
                    textView.setText("Nothing selected from the radio group");
                }
            }
        });
    }
}

4단계 — AndroidManifest.xml 확인

androidManifest.xml 파일에 아래와 같이 MainActivity가 정상적으로 등록되어 있는지 확인합니다.

<?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 스마트폰을 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run(실행) 아이콘을 클릭하세요. 실행 옵션 목록에서 연결된 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

Android에서 RadioGroup(라디오 그룹)의 선택된 항목 인덱스 가져오는 방법

Android에서 RadioGroup(라디오 그룹)의 선택된 항목 인덱스 가져오는 방법

Android에서 RadioGroup(라디오 그룹)의 선택된 항목 인덱스 가져오는 방법

라디오 버튼을 하나 선택한 상태에서 "Get Selected Radio Button" 버튼을 누르면 선택된 항목의 이름이 화면에 표시되고, 아무것도 선택하지 않은 상태에서 누르면 "Nothing selected from the radio group"이라는 안내 문구가 나타납니다.