使用动态创建的复选框

时间:2015-02-04 12:24:44

标签: android checkbox

我使用如下代码动态创建表格和复选框:

    for (Iterator i = users.iterator(); i.hasNext();) {
        Users p = (Users) i.next();

        /** Create a TableRow dynamically **/
        tr = new TableRow(this);
        /** Creating a Checkbox to add to the row **/
        CheckBox cb = new CheckBox(this);
        cb.setText(p.getEan());
        LinearLayout Ll1 = new LinearLayout(this);
        Ll1.addView(cb);
        System.out.println(j);
        tr.addView((View)Ll1); // Adding CheckBox to tablerow.  

        /** Creating a TextView to add to the row **/
        label = new TextView(this);
        label.setText(p.getName());
        label.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        label.setPadding(5, 5, 5, 5);
        label.setBackgroundColor(Color.GRAY);
        LinearLayout Ll = new LinearLayout(this);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT);
        params.setMargins(5, 2, 2, 2);
        Ll.addView(label,params);
        tr.addView((View)Ll); // Adding textView to tablerow.

         // Add the TableRow to the TableLayout
        tl.addView(tr, new TableLayout.LayoutParams(
                LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
    }

创建后,用户可以选中或取消选中。 通过检查,我需要为每个复选框运行另一个命令。

我的问题是,如何使用复选框?我怎么能“说话”,所以我可以使用它?

2 个答案:

答案 0 :(得分:0)

致电generateViewId()(或离开setId(i))并在setId()中使用生成的ID作为编程生成的复选框。在您的活动期间在本地保存ID并使用此ID与setOnCheckedChangeListener中来自R.的静态ID相同。

答案 1 :(得分:0)

您为行和复选框指定了相同的ID。不要给出行ID。或者不同的。

您可以在检查更改侦听器中放置以下代码。

LinearLayout my_layout = (LinearLayout)findViewById(R.id.my_layout);

for (int i = 0; i < Array_Count; i++) 
{
CheckBox checkBox = (CheckBox)my_layout.findViewById(i);

if ( checkBox == null )
    continue;

Toast.makeText(context, checkBox.getText(), Toast.LENGTH_SHORT).show(); 

checkBox.setText("my id is: " + i);
}