-3

有谁能够帮我?复选框不能动态创建。就像有时我使用程序创建 6 个复选框一样。有时我会创建 8 个复选框。我想为每个复选框设置一个事件以捕捉它被选中的时间。通过以下方式,我得到一个错误:不能引用在不同方法中定义的内部类中的非最终变量 i。更改“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();
                    }
                }
            };
4

2 回答 2

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

======编辑======

或试试这个

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]);
    }
于 2013-04-11T15:43:01.263 回答
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();
                }
            }
        };
于 2013-04-12T09:32:05.383 回答