IT/Android Studio

Android Studio s08RadioButtonDemo

Millennials 2020. 7. 1. 11:42

1)activity_main

 <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" >
        <RadioButton
            android:id="@+id/radio1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="가위"/>
        <RadioButton
            android:id="@+id/radio2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="바위"/>
        <RadioButton
            android:id="@+id/radio3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="보"/>
    </RadioGroup>

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.62" />

2)MainActivity.java

package kr.android.s08radiobuttondemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener{

    RadioGroup group;
    TextView tv;

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

        group = (RadioGroup)findViewById(R.id.radioGroup);
        tv = (TextView)findViewById(R.id.textView);

        //이벤트 연결
        group.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        //checkedId : 선택한 RadioButton의 id
        RadioButton rb = (RadioButton)findViewById(checkedId);
        tv.setText("당신의 선택 : "+rb.getText());
        
    }
}
반응형

'IT > Android Studio' 카테고리의 다른 글

Android Studio s12LinearLayoutDemo04  (0) 2020.07.01
Android Studio s11LinearLayoutDemo03  (0) 2020.07.01
Android Studio s07CheckBoxDemo  (0) 2020.07.01
Android Studio s06EditTextDemo  (0) 2020.07.01
Android Studio s05ImageViewDemo  (0) 2020.06.30