Simple Radio Button
Java Code
package com.example.project3;
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.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioButton rb1 = findViewById(R.id.r1);
RadioButton rb2 = findViewById(R.id.r1);
Button btn = findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
RadioGroup rg1 = findViewById(R.id.rg1);
int id = rg1.getCheckedRadioButtonId();
RadioButton rb = findViewById(id);
Toast.makeText(MainActivity.this, rb.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
XML Code
<?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"
tools:context=".MainActivity" >
<RadioGroup
android:layout_width="match_parent"
android:layout_height="543dp"
android:id="@+id/rg1">
<RadioButton
android:id="@+id/r1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Captain Team" />
<RadioButton
android:id="@+id/r2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Iron Man Team" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
</RadioGroup>
</LinearLayout>
Comments
Post a Comment