본문 바로가기
Android

[Android/Java] Radio Group, Radio Button 사용

by noddu 2022. 2. 10.
728x90
반응형

 

<RadioGroup
    android:id="@+id/Rad_mood"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintBottom_toTopOf="@+id/userBoard_content"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/userBoard_subject">

    <RadioButton
        android:id="@+id/rad_good"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="🥰"/>

    <RadioButton
        android:id="@+id/rad_soso"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="🙂"/>

    <RadioButton
        android:id="@+id/rad_bad"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="🥵"/>

 

Radio Group안에 Radio Button을 넣어준다

 


 

 

 

RadioGroup Rad_mood;
RadioButton rad_good, rad_soso, rad_bad;
Rad_mood = findViewById(R.id.Rad_mood);
rad_good = findViewById(R.id.rad_good);
rad_soso = findViewById(R.id.rad_soso);
rad_bad = findViewById(R.id.rad_bad);

 

Activity에서 선언해주고

 

TextView rad_result;

누른 Radio Button의 값을 저장할 TextView도 하나 만든다


 

Rad_mood.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i){
            case R.id.rad_good:
                rad_result.setText("2");
                break;
            case R.id.rad_soso:
                rad_result.setText("1");
                break;
            case R.id.rad_bad:
                rad_result.setText("0");
                break;
        }
    }
});

Radio Group의 setOnCheckedChangeListener를 만들어서

swith문으로 Radio Button을 클릭했을때의 값을 rad_result에 저장한다.

 

 


 

String mood = intent.getStringExtra("userBoard_mood");

난 rad_result를 mood라는 이름으로 받아왔다

 

 

if(mood.equals("2")){
    rad_good.setChecked(true);
}else if(mood.equals("1")){
    rad_soso.setChecked(true);
}else if(mood.equals("0")){
    rad_bad.setChecked(true);
}

rad_result에 조건을 걸어 저장된 번호로 checked가 된다

반응형