0

I want to add the dynamic checkbox in linear layout and the checkbox should become according to the size of JSON array from API.

my API response is like that :

[ { "id": 1, "alertName": "Device" }, { "id": 2, "alertName": "Email" } ]

Felix
  • 284
  • 2
  • 12

1 Answers1

1

Super Easy!

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/rooView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity"/>

item_checkbox.xml

<?xml version="1.0" encoding="utf-8"?>
<CheckBox
    android:id="@+id/checkbox"
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

MainActivity.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        var jsonArray = getJsonArray()

        for (i in 0 until jsonArray.length()) {
            var checkBox = LayoutInflater.from(this)
                .inflate(R.layout.item_checkbox, rooView, false) as CheckBox
            checkBox.text = jsonArray[i].toString()
            rooView.addView(checkBox)
        }


    }

    private fun getJsonArray(): JSONArray {
        var jsonObject: JSONObject = JSONObject()
        var jsonArray = JSONArray()

        jsonArray.put("Charlie")
        jsonArray.put("Buddy")
        jsonArray.put("Oscar")
        jsonArray.put("Milo")
        jsonArray.put("Archie")
        jsonArray.put("Ollie")

        jsonObject.put("pets", jsonArray)

        return jsonArray
    }
    }

Output enter image description here

JunaidKhan
  • 654
  • 7
  • 15
  • Junaid khan can you tell me how click listener is working of dynamic checkboxes – Ashish Pandey Jul 27 '20 at 13:34
  • KOTLIN https://stackoverflow.com/questions/44150185/kotlin-android-how-implement-checkbox-oncheckedchangelistener JAVA https://stackoverflow.com/questions/8386832/android-checkbox-listener – JunaidKhan Jul 27 '20 at 13:39