TOP
본문 바로가기
[Java]/Java Android

[Android] 컴파운드 버튼 2 - 라디오 버튼

by 기록자_Recordian 2025. 4. 30.
728x90
반응형
이전 내용
 

[Android] 컴파운드 버튼 1 - 체크 박스

이전 내용 [Android] 이벤트 리스너 예제이전 내용 [Android] 텍스트뷰 동적 생성이전 내용 [Android] 레이아웃 - 2 : 제약 레이아웃, 레이아웃 편집기이전 내용 [Android] 레이아웃 - 1이전 내용 [Android] 위젯

puppy-foot-it.tistory.com


라디오 버튼

 

라디오 버튼: 선택과 선택 해제의 두 가지 중 한 가지 상태를 나타내는 위젯으로, 라디오 버튼을 여러 개 묶어 라디오 그룹(Radio Group)으로 묶어 그룹화해서 사용한다.

라디오 버튼의 경우, 체크박스와 달리 상호 배타적이므로 하나의 라디오 버튼을 선택하면 나머지 라디오 버튼은 모두 자동으로 선택이 해제된다. ▶ 동일한 라디오 그룹에 속한 라디오 버튼에서는 하나만 선택 가능

 

[라디오 버튼의 속성 메소드]

  • boolean isChecked(): 체크박스의 현재 상태
  • void setChecked(boolean status): 체크박스의 상태 설정

라디오 버튼 예제

 

Q. 숫자를 입력하면 화씨 또는 섭씨로 변환해 주는 기능 구현하기

 

<LinearLayout 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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:id="@+id/edit_Input"/>
    
    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <RadioButton
            android:id="@+id/radioButton2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="11dp"
            android:minHeight="48dp"
            android:text="화씨" />

        <RadioButton
            android:id="@+id/radioButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="11dp"
            android:minHeight="48dp"
            android:text="섭씨" />

    </RadioGroup>

    <Button
        android:id="@+id/Button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="변환"
        android:background="#ff9800"
        android:onClick="onClicked" />

</LinearLayout>

 

 

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private EditText text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (EditText) findViewById(R.id.edit_Input);
    }

    public void onClicked(View view) {
        RadioButton celsiusButton = (RadioButton) findViewById(R.id.radioButton);
        RadioButton fahrenheitButton = (RadioButton) findViewById(R.id.radioButton2);

        // 입력값 검사
        if (text.getText().length() == 0) {
            Toast.makeText(this, "정확한 값을 입력하시오.", Toast.LENGTH_LONG).show();
            return; // 사용자에게 메시지를 보여줄 후 함수 종료
        }

        // 입력값 변환
        float inputValue = Float.parseFloat(text.getText().toString());

        if (fahrenheitButton.isChecked()) {
            // 섭씨로 변환
            text.setText(String.valueOf(convertFahrenheitToCelsius(inputValue)));
        } else if (celsiusButton.isChecked()) {
            // 화씨로 변환
            text.setText(String.valueOf(convertCelsiusToFahrenheit(inputValue)));
        }
    }

    // 화씨를 섭씨로 변환하는 메서드
    private float convertFahrenheitToCelsius(float fahrenheit) {
        return ((fahrenheit - 32) * 5 / 9);
    }

    // 섭씨를 화씨로 변환하는 메서드
    private float convertCelsiusToFahrenheit(float celsius) {
        return ((celsius * 9) / 5) + 32;
    }
}

- onClicked():

  • onClicked: UI에서 버튼 클릭 시 호출되는 메서드. 사용자가 선택한 라디오 버튼에 따라 온도를 변환.
  • 라디오 버튼 참조: 두 개의 RadioButton을 각각 섭씨와 화씨를 선택하기 위해 가져옴.
  • 입력값 검사: 사용자가 EditText에 값을 입력하지 않았다면, Toast 메시지를 통해 알림을 제공하고 메서드를 종료.
  • 입력값 변환: Float.parseFloat을 사용하여 입력 문자열을 부동 소수점 숫자로 변환.
  • 변환 로직:
    선택된 라디오 버튼이 화씨일 경우, convertFahrenheitToCelsius 메서드를 호출하여 섭씨로 변환.
    섭씨가 선택된 경우, convertCelsiusToFahrenheit 메서드를 호출하여 화씨로 변환.
※ Toast는 Android 애플리케이션에서 사용자에게 간단한 정보를 제공하기 위해 사용되는 UI 컴포넌트. 사용자가 특정 작업(예: 버튼 클릭, 데이터 입력 등)을 수행한 후 결과나 알림 메시지를 짧게 표시하는 데 유용.

 

- 변환 메소드

  • convertFahrenheitToCelsius: 화씨 온도를 섭씨로 변환하는 메서드. 수식 (fahrenheit - 32) * 5 / 9
  • convertCelsiusToFahrenheit: 섭씨 온도를 화씨로 변환하는 메서드. 수식 (celsius * 9) / 5 + 32

[실행]


다음 내용

 

[Android] 컴파운드 버튼 3 - 토글 버튼

이전 내용 [Android] 컴파운드 버튼 2 - 라디오 버튼이전 내용 [Android] 컴파운드 버튼 1 - 체크 박스이전 내용 [Android] 이벤트 리스너 예제이전 내용 [Android] 텍스트뷰 동적 생성이전 내용 [Android] 레이

puppy-foot-it.tistory.com

728x90
반응형