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" } ]

4
  • based on received json array size, create them. Commented Jul 27, 2020 at 5:08
  • @notTdar unable to get logic. if you have any logic please share me once Commented Jul 27, 2020 at 5:12
  • for(int i =0; i<jsonArray.length(); i++) { // CheckBox cb = new CheckBox(); }; Commented Jul 27, 2020 at 5:15
  • recycleview willl do same as you want. Commented Jul 27, 2020 at 5:26

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Junaid khan can you tell me how click listener is working of dynamic checkboxes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.