无法从动态添加的复选框中获取值

时间:2014-04-04 06:35:24

标签: android dynamic checkbox

点击我添加了一个复选框的按钮,最后需要通过点击提交按钮获取所有选中的复选框值,

这是我的代码

mIncrementButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

                params.setMargins(20, 0, 0, 0);

                CheckBox checkbox = new CheckBox(MainActivity.this);

                checkbox.setLayoutParams(params);
                mAllText.add(checkbox);
                checkbox.setText("Checkbox" + j);

                checkboxlayout.addView(checkbox);
                j++;

                Log.d("j", "--->" + j);

            }
        });

        mGetTheVlue.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Log.d("Inside Button", "Inside Burron" + mAllText.size());

                for (int i = 0; i < mAllText.size(); i++) {
                    CheckBox check = mAllText.get(i);
                    if (check.isChecked()) {
                        AllCheckbox.add(check.getText().toString());
                    }

                }

            }
        });

现在我需要检查是否已选中所有复选框并需要获取值, 不知道这个问题是否过时。但我得到谷歌的任何解决方案,请帮助我们获得解决方案。

提前致谢。

1 个答案:

答案 0 :(得分:7)

此外,您不需要将所有CheckBox存储在Collection中。您可以从布局中获取子视图,并检查每个视图是否为CheckBox。

    mGetTheVlue.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Log.d("Inside Button", "Inside Burron" + checkboxlayout.getChildCount());

            for(int i=0; i<checkboxlayout.getChildCount(); i++) {
                View nextChild = checkboxlayout.getChildAt(i);

                if(nextChild instanceOf CheckBox)
                {
                    CheckBox check = (CheckBox) nextChild;
                    if (check.isChecked()) {
                                AllCheckbox.add(check.getText().toString());
                    }
                }

        }

        }
    });
相关问题