Saturday, August 8, 2015

How to use RadioButton click event in Android

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#fff3e1"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Which is your most favorite?"
        />
    <RadioGroup
        android:id="@+id/rg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_below="@id/tv"
        >
        <RadioButton
            android:id="@+id/rb_coldfusion"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ColdFusion"
            android:onClick="onRadioButtonClicked"
            />
        <RadioButton
            android:id="@+id/rb_flex"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Flex"
            android:onClick="onRadioButtonClicked"
            />
    </RadioGroup>
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.view.View;

public class MainActivity extends Activity{

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

    public void onRadioButtonClicked(View v){
        RadioGroup rg = (RadioGroup) findViewById(R.id.rg);
        RadioButton rb_coldfusion = (RadioButton) findViewById(R.id.rb_coldfusion);
        RadioButton rb_flex = (RadioButton) findViewById(R.id.rb_flex);

        // Is the current Radio Button checked?
        boolean checked = ((RadioButton) v).isChecked();

        switch(v.getId()){
            case R.id.rb_coldfusion:
                if(checked)
                    rb_coldfusion.setTextColor(Color.RED);
                    rb_flex.setTextColor(Color.GRAY);
                    break;

            case R.id.rb_flex:
                if(checked)
                    rb_flex.setTextColor(Color.RED);
                    rb_coldfusion.setTextColor(Color.GRAY);
                    break;
        }
    }
}
More android examples