Set padding on CheckBox in android programmatically

How to add left, right, top, bottom side padding in dp to checkbox in android dynamically.

In this tutorial we are simply creating three check boxes and after that with the use of setPadding() method we are setting up left side, right side, top side, bottom side padding on CheckBox . So here is the complete step by step tutorial for Set padding on CheckBox in android programmatically.

android-project-download-code-button

How to Set padding on CheckBox in android programmatically.

Code for MainActivity.java file.

 package com.setpaddingcheckbox_android_examples.com;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CheckBox;

public class MainActivity extends Activity {

 CheckBox CheckBox1,CheckBox2,CheckBox3;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 CheckBox1 = (CheckBox)findViewById(R.id.checkBox1);
 CheckBox2 = (CheckBox)findViewById(R.id.checkBox2);
 CheckBox3 = (CheckBox)findViewById(R.id.checkBox3);
 
 //Adding padding on Checkbox.
 CheckBox1.setPadding(40,20,20,20);
 CheckBox2.setPadding(40, 20, 20, 20);
 CheckBox3.setPadding(40, 20, 20, 20);
 
 }
}

Code for activity_main.xml layout file.

 <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"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.setpaddingcheckbox_android_examples.com.MainActivity" >

 <CheckBox
 android:id="@+id/checkBox1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 android:text="CheckBox-1"
 />

 <CheckBox
 android:id="@+id/checkBox2"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignLeft="@+id/checkBox1"
 android:layout_below="@+id/checkBox1"
 android:text="CheckBox-2" />

 <CheckBox
 android:id="@+id/checkBox3"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignLeft="@+id/checkBox2"
 android:layout_below="@+id/checkBox2"
 android:text="CheckBox-3" />

</RelativeLayout>

Screenshot:

Set padding on CheckBox in android programmatically

Click here to download Set padding on CheckBox in android programmatically project with source code.

Leave a Reply

Your email address will not be published. Required fields are marked *