MainActivity.java
package com.example.youtuberadio;
import androidx.appcompat.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;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
RadioButton radioButton;
RadioGroup radioGroup;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup=findViewById(R.id.rGroup);
textView=findViewById(R.id.view_selected);
//variable for the button
Button buttonOk =findViewById(R.id.btn_ok);
buttonOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int radioId=radioGroup.getCheckedRadioButtonId();
radioButton=findViewById(radioId);
textView.setText("You selected: "+radioButton.getText());
}
});
}
public void checkOk(View v){
int radioId=radioGroup.getCheckedRadioButtonId();
radioButton=findViewById(radioId);
Toast.makeText(this,"You have clicked on: "+ radioButton.getText(),Toast.LENGTH_SHORT).show();
}
}
Activity_Main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".MainActivity">
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/rGroup"
android:layout_centerInParent="true">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/male"
android:text="Male"
android:onClick="checkOk"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/female"
android:text="Female"
android:onClick="checkOk"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/other"
android:text="Other"
android:onClick="checkOk"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/rather"
android:text="Rather Not Say"
android:onClick="checkOk"
android:checked="true"/>
</RadioGroup>
<TextView
android:id="@+id/view_selected"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/rGroup"
android:layout_marginStart="141dp"
android:layout_marginLeft="141dp"
android:layout_marginTop="-4dp"
android:text="Your choice"
android:textSize="20sp" />
<Button
android:id="@+id/btn_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/view_selected"
android:layout_marginStart="145dp"
android:layout_marginLeft="145dp"
android:layout_marginTop="0dp"
android:text="OK" />
</RelativeLayout>
Comments
Post a Comment