How to dynamically add or remove CheckBox from parent View in Kotlin

In this android kotlin source code example, we are going to dynamically add or remove CheckBox from parent View in Kotlin.

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

Below is a step by step source code to dynamically add or remove CheckBox from parent View in Kotlin.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context=".CheckBox.CheckBoxActivity6">

</LinearLayout>

MainActivity.kt

import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.ViewGroup
import android.widget.Button
import android.widget.CheckBox
import android.widget.LinearLayout
import androidx.core.view.marginBottom
import com.bluapp.kotlinview.R

class CheckBoxActivity6 : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_check_box6)
        val linearLayout = findViewById(R.id.linearLayout) as LinearLayout

        val llParam = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )

        val addButton = Button(this)
        addButton.text= "Add CheckBox"
        addButton.setTextColor(Color.WHITE)
        addButton.setBackgroundColor(resources.getColor(R.color.colorAccent))
        llParam.setMargins(0,0,0,10)
        linearLayout.addView(addButton, llParam)

        val removeButton = Button(this)
        removeButton.text= "Remove CheckBox"
        removeButton.setTextColor(Color.WHITE)
        removeButton.setBackgroundColor(resources.getColor(R.color.colorAccent))
        llParam.setMargins(0,0,0,10)
        linearLayout.addView(removeButton, llParam)

        addButton.setOnClickListener {
            val checkbox = CheckBox(this)
            checkbox.tag="CheckBoxTag"
            checkbox.text="CheckBox"
            linearLayout.addView(checkbox)
        }

        removeButton.setOnClickListener {
            val getcheckbox = linearLayout.findViewWithTag<CheckBox>("CheckBoxTag")
            linearLayout.removeView(getcheckbox)
        }
    }
}

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