Sunday, August 9, 2015

How to change CheckBox text and background 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="#81c08a"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Check your favorites?"
        />
    <CheckBox
        android:id="@+id/cb_coldfusion"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ColdFusion"
        android:layout_below="@id/tv"
        android:paddingRight="15dp"
        />
    <CheckBox
        android:id="@+id/cb_flex"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Flex"
        android:layout_below="@id/cb_coldfusion"
        android:textColor="@android:color/holo_red_dark"
        android:background="#ffc38d"
        android:paddingRight="15dp"
        />
    <CheckBox
        android:id="@+id/cb_flash"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Flash"
        android:layout_below="@id/cb_flex"
        android:paddingRight="15dp"
        />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change CheckBox Color"
        android:layout_below="@id/cb_flash"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;

public class MainActivity extends Activity {

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

        final CheckBox cb_flash = (CheckBox) findViewById(R.id.cb_flash);
        Button btn = (Button) findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Set the Flash CheckBox Text Color
                cb_flash.setTextColor(Color.BLUE);

                // Set the Flash CheckBox Background Color
                cb_flash.setBackgroundColor(Color.parseColor("#cbff75"));
            }
        });
  }
}
More android examples