Sunday, August 9, 2015

How to add padding to a CheckBox 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="#d0a718"
    >
    <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:padding="10dp"
        android:background="#cbe7ff"
        />
    <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:background="#ffd4f0"
        />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set Flex CheckBox Padding"
        android:layout_below="@id/cb_flex"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

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);

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

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Add padding programmatically to Flex CheckBox
                // left, top and bottom side 25 pixel and right 100 pixel
                cb_flex.setPadding(25,25,100,25);
            }
        });
 }
}
More android examples