根据字符串数组大小创建复选框

时间:2014-07-10 11:28:25

标签: android arrays string checkbox

我刚开始学习android应用程序开发。我正在查看复选框并探讨动态创建它的各种可能性等等。 现在,出于好奇,我有一个小疑问。 题 : 假设我在一个字符串数组中有10个项目,每个项目都有自己的名字。现在,我需要知道的是......我可以手动为这10个项目实现复选框。但我的问题是,说我列出了100个项目,每个项目都有唯一的名称。我想在读取字符串数组中的项目数时动态创建复选框,并将每个复选框的文本设置为我的相应读取项目字符串数组。

示例:说我有4个名字。 Apple,Google,Microsoft,Linux。 现在在我的活动中,我想动态设置4复选框,并将每个复选框的文本设置为这四个值。我们将不胜感激为此问题提供一般化解决方案(即扩展任意数量项目的代码)。

对此的任何帮助都非常感谢。感谢那些天才开发者,我很高兴能成为这个论坛的一员。这个论坛教会了我那些令人难以置信的开发人员的很多东西。

1 个答案:

答案 0 :(得分:1)

的活动:

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);
        }
    }
}

布局:

<?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>