Android - 如何在动态添加的LinearLayouts中获取CheckBoxes的检查状态?

时间:2018-03-26 16:09:20

标签: android checkbox android-linearlayout android-checkbox

我想知道,我有一个垂直的LinearLayout,我在其中动态添加水平LinearLayouts。每个水平LinearLayout都包含一个CheckBox。我想知道,如何在每个动态添加的LinearLayout中检索每个CheckBox的已检查状态?

   for (int i = 0; i < array.size(); i++) {
            LayoutInflater layoutInflater = (LayoutInflater)
                    this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            LinearLayout testView = (LinearLayout) layoutInflater.inflate(R.layout.balance_test_layout, null);
            for (int j = 0; j < customConditions.size(); j++) {
                TextView checkView = new TextView(BalanceActivity.this);
                checkView.setPadding(padding, padding, padding, padding);
                checkView.setTextSize(20);

                checkView.setGravity(Gravity.CENTER);

                LinearLayout.LayoutParams checkTextParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45, getResources().getDisplayMetrics())));

                checkTextParams.gravity = Gravity.CENTER;
                checkView.setLayoutParams(checkTextParams);

                testView.addView(checkView);


            }


            CheckBox option = (CheckBox) testView.findViewById(R.id.testCheckBox);
            option.setId(i);
            option.setText(array.get(i));

        //code for of rest of LinearLayout
   }

     okButton.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //need to get values of CheckBoxes in here
                    }
     });

1 个答案:

答案 0 :(得分:0)

我明白了:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)

    var info = fetchCoinInfo[indexPath.row]
    cell.textLabel?.text = info["name"] as? String
    cell.detailTextLabel?.text = info["symbol"] as? String

    if let checked = info["checked"] as? Bool, checked == true {
        cell?.accessoryType = .checkmark
    }else {
        cell?.accessoryType = .none
        info["checked"] = false
    }

    return cell

}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    tableView.deselectRow(at: indexPath, animated: true)
    let cell = tableView.cellForRow(at: indexPath)
    var info = fetchCoinInfo[indexPath.row]
    if cell?.accessoryType == .checkmark {
        cell?.accessoryType = .none
        info["checked"] = false
    }else {
        cell?.accessoryType = .checkmark
        info["checked"] = true
    }

}