How to programmatically add or remove CheckBox in Android

In this android programming source code example, we are going to programmatically add or remove CheckBox in Android.

You can copy and adopt this source code example to your android project without reinventing the wheel.

Below is a step by step source code to programmatically add or remove CheckBox in Android.

MainActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

public class CheckBox6 extends AppCompatActivity {

    private LinearLayout linearLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);

        TextView tv = new TextView(this);
        tv.setText("Add and Remove Checkbox Programmatically");
        tv.setPadding(20, 20, 20, 20);
        linearLayout.addView(tv);

        Button addButton = new Button(this);
        addButton.setText("Add Checkbox dynamically");
        linearLayout.addView(addButton);

        Button removeButton = new Button(this);
        removeButton.setText("Remove Checkbox");
        linearLayout.addView(removeButton);

        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CheckBox firstCheckBox = new CheckBox(getApplicationContext());
                firstCheckBox.setTag("First CheckBox");
                firstCheckBox.setText("Checkbox");
                linearLayout.addView(firstCheckBox);
            }
        });

        removeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CheckBox retrieveFirstCheckBox = ll.findViewWithTag("First CheckBox");
                linearLayout.removeView(retrieveFirstCheckBox);
            }
        });

        this.setContentView(linearLayout);
    }
}

 

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment