复选框无法动态创建

时间:2013-04-11 15:28:47

标签: android android-checkbox

任何人都可以帮助我吗?复选框无法动态创建。就像有时我使用程序创建6个复选框。有时我会创建8个复选框。我想设置每个复选框一个事件来捕获它被检查的时间。在下面的方式中,我得到一个错误:不能引用在另一个方法中定义的内部类中的非最终变量。变换修饰符“i “到最后。 mCheckTime是一个长数组。

        for(int i=0;i<optionsNum;i++){
            mCheckBox[i]=new CheckBox(this);
            mCheckBox[i].setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){
                public void onCheckedChanged(CompoundButton buttonView, boolean isCheck){
                    if (mCheckBox[i].isChecked()) {
                        mCheckTime[i] = System.currentTimeMillis();
                    }
                }
            };

2 个答案:

答案 0 :(得分:2)

如果您的内容视图是LinearLayout,请尝试

final CheckBox mCheckBox = new CheckBox(this);
    mCheckBox
            .setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
                public void onCheckedChanged(CompoundButton buttonView,
                        boolean isCheck) {
                    if (mCheckBox.isChecked()) {
                        mCheckBox.setText(System.currentTimeMillis() + "");
                    }
                }
            });
    LayoutParams params = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT);
    addContentView(mCheckBox, params);

====== EDIT ==

或试试这个

LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
    setContentView(layout);
    CheckBox[] mCheckBox = new CheckBox[6];
    for (int i = 0; i < 6; i++) {
        mCheckBox[i] = new CheckBox(this);
        mCheckBox[i].setText(i + "");
        mCheckBox[i]
                .setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
                    public void onCheckedChanged(CompoundButton buttonView,
                            boolean isCheck) {
                        if (isCheck) {
                            Toast.makeText(MainActivity.this,
                                    System.currentTimeMillis() + "",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
        layout.addView(mCheckBox[i]);
    }

答案 1 :(得分:0)

非常感谢你。我使用最终变量j来替换内部类中的i。

for(int i=0;i<optionsNum;i++){
        final int j = i;
        mCheckBox[i]=new CheckBox(this);
        mCheckBox[i].setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){
            public void onCheckedChanged(CompoundButton buttonView, boolean isCheck){
                if (mCheckBox[i].isChecked()) {
                    mCheckTime[i] = System.currentTimeMillis();
                }
            }
        };