5

我正在尝试将复选框动态添加到 LinearLayout。我使用了以下代码,

private class ListAdapters extends ArrayAdapter<ApplicationBean> {
private ArrayList<ApplicationBean> items;
private int position;

public ListAdapters(Context context, int textViewResourceId,
        ArrayList<ApplicationBean> mTitleList) {
    super(context, textViewResourceId, mTitleList);
    this.items = mTitleList;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    this.position = position;
    if (v == null) {
        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.applicationlistitem, null);
    }

    final ApplicationBean o = (ApplicationBean) items.get(position);

    if (o != null) {

        txtAppName = (TextView) v.findViewById(R.id.app_name);
        txtAppName.setText("" + o.getAppName());
        launchButton = (Button) v.findViewById(R.id.launch_btn);
        launchButton.setTag(position);
        launchButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                final PackageManager pm = mContext.getPackageManager();
                Intent LaunchIntent = pm
                        .getLaunchIntentForPackage(items
                                .get(Integer.parseInt(v.getTag()
                                        .toString())).getPname());
                mContext.startActivity(LaunchIntent);

            }
        });

        rdgPassFail = (RadioGroup) v.findViewById(R.id.status_group);
        rdgPassFail.setTag(position);

        RadioButton passBtn = (RadioButton) v
                .findViewById(R.id.pass_btn);
        passBtn.setTag(position);
        RadioButton failbtn = (RadioButton) v
                .findViewById(R.id.fail_btn);
        failbtn.setTag(position);

        rdgPassFail
                .setOnCheckedChangeListener(new OnCheckedChangeListener() {

                    @Override
                    public void onCheckedChanged(RadioGroup group,
                            int checkedId) {
                        ApplicationBean o = (ApplicationBean) items
                                .get(Integer.parseInt(group.getTag()
                                        .toString()));

                        switch (checkedId) {
                        case R.id.fail_btn:
                            Log.e("Fail button", "Clicked");
                            o.setFailState(true);
                            o.setPassState(false);
                            numOptions = 0;
                            Log.e("Fail button--1", "Clicked");

                            break;
                        case R.id.pass_btn:
                            Log.e("Pass button", "Clicked");

                            o.setFailState(false);
                            o.setPassState(true);
                            Log.e("Pass button-----1", "Clicked");

                            break;
                        }
                        items.set(Integer.parseInt(group.getTag()
                                .toString()), o);
                    }

                });

            Log.i("checkBoxFlag", "checkBoxFlag not true " + position);
            LinearLayout featuresTable = (LinearLayout) v
                    .findViewById(R.id.failure_reasonslist);


            for (int i = 0; i <= 5; i++) {
                CheckBox feature1 = new CheckBox(this.getContext());
                featuresTable.addView(feature1);
                Log.i("Inside for loop", "creating check box " + position);
            }
            checkBoxFlag = true;

        txtDescription = (EditText) v
                .findViewById(R.id.description_text);
        txtDescription.setTag(position);
        if (txtDescription.isFocused()) {
            InputMethodManager inputManager = (InputMethodManager) mContext
                    .getSystemService(INPUT_METHOD_SERVICE);
            inputManager.restartInput(txtDescription);
        }

        txtDescription
                .setOnFocusChangeListener(new View.OnFocusChangeListener() {

                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (!hasFocus) {

                            final EditText Caption = (EditText) v;
                            o.setDescription(Caption.getText()
                                    .toString());

                        }

                    }
                });
        uninstallButton = (Button) v.findViewById(R.id.uninstall_btn);
        uninstallButton.setTag(position);
        // uninstallButton.setVisibility(View.INVISIBLE);
        o.setUninstallVisible(false);
        uninstallButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Uri packageUri = Uri.parse("package:"
                        + items.get(
                                Integer.parseInt(v.getTag().toString()))
                                .getPname());
                Intent uninstallIntent = new Intent(
                        Intent.ACTION_DELETE, packageUri);
                uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(uninstallIntent);
                mTitleList.remove(items.get((Integer) v.getTag()));

                mListView.setAdapter(new ListAdapters(mContext,
                        R.id.app_name, mTitleList));
                ((BaseAdapter) mListView.getAdapter())
                        .notifyDataSetChanged();
                isUninstallclicked = true;

            }
        });

        submitButton = (Button) v.findViewById(R.id.submit_btn);
        submitButton.setTag(txtDescription);
        submitButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                EditText tv = (EditText) v.getTag(); // get edittext
                                                        // object

                txtDescription = tv;
                if (txtTesterName.getText().toString().equals("")) {
                    showDialog("Please enter the name of tester",
                            mContext);
                } else if (numOptions == 0) {
                    showDialog("Please select failure reason", mContext);
                } else if (tv.getText().toString().equals("")) {
                    showDialog("Please enter the description", mContext);
                } else if (!isNetworkAvailable()) {

                    showDialog(
                            "No network connection.Report won't be submitted",
                            mContext);
                } else {

                    if (!o.isUninstallVisible()) {
                        uninstallButton.setVisibility(View.VISIBLE);
                        o.setUninstallVisible(true);
                        mListView.invalidate();
                    }
                    PostRequest p = new PostRequest(Integer.parseInt(tv
                            .getTag().toString()));
                    p.execute();

                }
            }

        });

    }
    return v;
}

@Override
public int getItemViewType(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public int getViewTypeCount() {
    // TODO Auto-generated method stub
    return items.size();
}

}

根据代码,视图中应该有六个复选框。但是当我检查它的六个以上复选框时。请在下面找到日志(从 logcat 复制)。日志也来了两次。我在列表视图中有一些其他控件。这些是在布局 xml 中定义的。但是我不能在设计时限制这些复选框的数量。所以我试图动态加载。有人可以帮忙吗?

10:40:23.163: I/Inside for loop(440): creating check box 0
10:40:23.223: I/Inside for loop(440): creating check box 0
10:40:23.223: I/Inside for loop(440): creating check box 0
10:40:23.273: I/Inside for loop(440): creating check box 0
10:40:23.273: I/Inside for loop(440): creating check box 0
10:40:23.303: I/Inside for loop(440): creating check box 0
10:40:23.393: I/c
10:40:23.393: I/Inside for loop(440): creating check box 0
10:40:23.423: I/Inside for loop(440): creating check box 0
10:40:23.423: I/Inside for loop(440): creating check box 0
10:40:23.503: I/Inside for loop(440): creating check box 0
10:40:23.503: I/Inside for loop(440): creating check box 0
10:40:23.553: I/Inside for loop(440): creating check box 0
4

6 回答 6

9

您必须尝试以下代码来创建动态复选框

int Array_Count=0;
String[] Str_Array;

Array_Count=Str_Array.length;

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

for (int i = 0; i < Array_Count; i++) 
{
    TableRow row =new TableRow(this);
    row.setId(i);
    row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
    CheckBox checkBox = new CheckBox(this);
    checkBox.setOnCheckedChangeListener(this);
    checkBox.setId(i);
    checkBox.setText(Str_Array[i]);
    row.addView(checkBox);  
    my_layout.addView(row);
}
于 2012-11-05T05:53:56.790 回答
4

这样做

    @Override
    public void onCreate(Bundle savedInstanceState) {
    LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout2);

    //add checkboxes
            for(int i = 0; i < 6; i++) {
                CheckBox cb = new CheckBox(this);
                cb.setText("Dynamic Checkbox " + i);
                cb.setId(i+6);
                ll.addView(cb);
            }
    }
于 2012-11-05T05:29:59.020 回答
0

用这个:

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

        CheckBox[] cb = new CheckBox[6];
        for (int i = 0; i < 6; i++) {
            cb[i] = new CheckBox(this);
            ll.addView(cb[i]);
            cb[i].setText("Dynamic Checkbox " + i);
            cb[i].setId(i + 6);

        }
于 2013-06-11T15:17:47.170 回答
0

您清楚发布的代码仅添加了 6 个复选框。这意味着调用这些函数的方法被调用了两次。

您正在某处记录 I/c。该方法的第二次调用是在该调用之后进行的,这为您提供了一个开始查找的位置。

于 2012-11-05T05:29:25.680 回答
0

尝试这个: -

CheckBox[] cb=new CheckBox[6];
for(int i = 0; i < 6; i++) {
cb[i].setText("Dynamic Checkbox " + i);
cb[i].setId(i+6);
linearLayout.addView(cb[i]);

}
于 2012-11-05T05:46:55.660 回答
0

在科特林

    fun createCheckbox() {
    var arr_cb = arrayOfNulls<CheckBox>(checkbox_size)
    val layout = findViewById<View>(R.id.layout_checkbox) as ViewGroup
    val ll = LinearLayout(this)
    ll.orientation = LinearLayout.VERTICAL

    for (i in 0 until arr_cb.size) {
        arr_cb[i] = CheckBox(this)
        arr_cb[i]?.text = health_status.get(i).toString()
        arr_cb[i]?.setPadding(25, 0, 0, 0)
        arr_cb[i]?.id = i
        arr_cb[i]?.tag = health_status[i]
        arr_cb[i]?.setTextColor(resources.getColor(R.color.title_color))
        arr_cb[i]?.setOnCheckedChangeListener(
            arr_cb[i]?.let {
                handleCheck(it)
            })

        arr_cb[i]?.buttonTintList =
            ColorStateList.valueOf(resources.getColor(R.color.theme_color))
        ll.addView(arr_cb[i])
    }
    layout.addView(ll)
}

OnCheckedChangeListener 的 handleCheck 方法

    private fun handleCheck(chk: CheckBox): CompoundButton.OnCheckedChangeListener? {
    return object : CompoundButton.OnCheckedChangeListener {
        override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
            if (!isChecked) {
                //uncheck
            } else {
                //check
            }
        }
    }
}
于 2021-03-24T10:45:07.717 回答