반응형

Ex05RadioButton

안드로이드 네이티브 앱 개발 수업 예제#5

주요코드

RadioButton, RadioGroup, RatingBar 알아보기

  • res폴더>>layout폴더안에 있는 activity_main.xml문서를 수정하여 화면제작
  • RadioButton 3개와 Button 1개, TextView 1개를 만들어 버튼이 클릭되었을 때 선택(Selected)되어 있는 RadioButton의 텍스트를 얻어와 TextView에 표시하기
  • RadioButton을 그냥 3개만들면 Single choice가 되지 않음. 라디어버튼3개가 하나의 그룹이 되도록 3개를 감싸는 RadioGroup뷰를 사용해야만 함.
  • RadioButton의 선택(Selected)상태가 변경될 때마다 선택된 체크박스의 텍스트를 표시하기
  • RadioButton이 아니라 RadioGroup에 리스너를 설정해야함. 선택상태 변경 리스너 객체 RadioGroup.OnCheckedChangeListener 소개
  • RatingBar 위젯의 사용법은 다른 복합버튼들과 비슷함. 다만, 레이팅값의 변화 리스너객체 OnRatingBarChangeListener를 사용해야하는 것이 다름.

실행모습

 

 

실행모습 GIF

 

 

소스코드

# activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">

    <RadioGroup
        android:id="@+id/rg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/rb_kor"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="KOREA"/>
        <RadioButton
            android:id="@+id/rb_chana"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="CHINA"/>
        <RadioButton
            android:id="@+id/rb_japan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="JAPAN"/>

    </RadioGroup>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="OK"
        android:onClick="clickBtn"/>

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="result"
        android:textSize="20sp"
        android:textStyle="bold"/>

    <RatingBar
        android:id="@+id/rating"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="5"
        android:rating="3.5"
        android:stepSize="0.5"/>


</LinearLayout>

 

 

# MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RatingBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView tv;
    RadioGroup rg;

    RatingBar ratingBar;

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

        tv= findViewById(R.id.tv);
        rg= findViewById(R.id.rg);

        //RadioButton의 체크상태가 변경될 때 마다 반응하기
        //라디오버튼 사용은 Single choice이므로 개별 버튼에 리스너를 적용하여 잘 사용하지 않음 [물론, 원한다면 체크박스처럼 개별 라디오버튼에 리스터를 설정해도 됨]
        //RadioButton이 아니라 RadioGroup에게 OnCheckedChangeListener를 설정해야 함.
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {

                //체크된 RadioButton 찾아오기
                RadioButton rb= findViewById(checkedId);

                //체크된 라디오버튼의 글씨를 얻어와서 텍스트뷰에 보여주기
                tv.setText( rb.getText().toString() );

            }
        });

        //RatingBar 제어하기 - 레이팅점수 변경 리스너 사용
        ratingBar= findViewById(R.id.rating);
        ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {

            //2번째 파라미터 : 사용자가 터치를 이용해서 설정된 rating 값 (소수점 존재함. float형)
            //3번째 파라미터 : 사용자가 터치를 이용해서 점수를 변경했는지 여부
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean byUser) {
                tv.setText(rating+"점");
            }
        });

    }

    public void clickBtn(View view) {
        //체크되어 있는 RadioButton 찾아오기
        int id= rg.getCheckedRadioButtonId();
        RadioButton rb= findViewById(id);

        //체크된 라디오버튼의 글씨를 얻어와서 텍스트뷰에 보여주기
        tv.setText( rb.getText().toString() );
    }

}
반응형

+ Recent posts