Reputation: 79
I am just starting to learn android application development. I was looking through the checkbox and probing on various possibilities of dynamically creating it and much more. Now, I have a small doubt out of curiosity. QUESTION : Say I have 10 items in a string array with each one having their own names. Now , all I needed to know is.. I can implement checkbox manually for these 10 items. But my question is , Say I have 100 items listed with each one having unique name.I want to create checkbox dynamically on reading the number of items in my string array and also to set the text of each checkbox to the correspondingly read item in my string array.
Example: say I have 4 names. Apple, Google, Microsoft, Linux. Now in my activity i wanted to set 4 checkbox dynamically and set the text of each checkbox to these four values. A generalized solution (i.e. to expand your code for any number of items) for this question will be appreciated .
Any help on this is highly appreciated. Thanks to those genius developers out there and I am so happy to be a part of this forum as well. This forum has taught me so many things with those incredible developers out there.
Upvotes: 1
Views: 2281
Reputation: 6857
Activity:
public class CheckboxActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_checkbox);
String[] array = new String[]{"Apple", "Google"};
ViewGroup checkboxContainer = (ViewGroup) findViewById(R.id.checkbox_container);
for (int i = 0; i < array.length; i++) {
CheckBox checkBox = new CheckBox(this);
checkBox.setText(array[i]);
checkboxContainer.addView(checkBox);
}
}
}
layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/checkbox_container"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
Upvotes: 1