Screenshots :
activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.chantisandroid.radiobutton.MainActivity">
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radioGroup"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radioButton"
android:checked="false"
android:text="Male" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:id="@+id/radioButton2"
android:layout_marginTop="20dp"
android:checked="false" />
</RadioGroup>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Gender"
android:id="@+id/textView"
android:layout_alignRight="@+id/radioGroup"
android:layout_alignEnd="@+id/radioGroup"
android:layout_alignParentTop="true"
android:layout_alignLeft="@+id/radioGroup"
android:layout_alignStart="@+id/radioGroup"
android:layout_marginTop="30dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select"
android:id="@+id/button_select"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
MainActivity.java :
package com.chantisandroid.radiobutton;
import android.support.v7.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 implements View.OnClickListener {
RadioGroup radioGroup;
RadioButton radioButton;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
button = (Button)findViewById(R.id.button_select);
button.setOnClickListener(this);
}
@Override
public void onClick(View view) {
int select = radioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton)findViewById(select);
Toast.makeText(this,radioButton.getText(),Toast.LENGTH_LONG).show();
}
}
No comments:
Post a Comment