Saturday, August 8, 2015

How to change RadioButton text color 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="#f2ffdd"
    >
    <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:textColor="@android:color/holo_red_dark"
            />
        <RadioButton
            android:id="@+id/rb_flex"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Flex"
            android:textColor="@android:color/holo_red_dark"
            />
    </RadioGroup>
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Radio Button Text Color"
        android:onClick="perform_action"
        android:layout_below="@id/rg"
        />
</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.view.View;

public class MainActivity extends Activity {

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

    public void perform_action(View v) {

        RadioButton rb_coldfusion = (RadioButton) findViewById(R.id.rb_coldfusion);
        RadioButton rb_flex = (RadioButton) findViewById(R.id.rb_flex);

        // Set the Radio Button text color
        rb_coldfusion.setTextColor(Color.GREEN);

        // Set the Radio Button text color from hex string
        rb_flex.setTextColor(Color.parseColor("#0000FF"));
    }
}
More android examples