【问题标题】:Dynamic list of checkboxes with onclick functions具有 onclick 功能的复选框的动态列表
【发布时间】:2014-05-05 12:35:57
【问题描述】:

我有一个从数据库返回项目列表的页面。我想通过 onClick 将每个项目作为复选框动态添加到我的 android 片段中,这可以判断项目是被选中还是未选中。

如何动态添加带有点击次数和不同标题的复选框?

下面是我将复选框插入的 xml:

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="#e5e5e5"

    android:layout_height="match_parent" >

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >




        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="6dp"
                android:layout_marginRight="6dp"
                android:layout_marginTop="4dp"
                android:layout_marginBottom="4dp"
                android:orientation="vertical"
                android:background="@drawable/bg_card">

                <!-- Card Contents go here -->


                <TextView
                    android:id="@+id/styleDescription"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:textSize="15sp"
                    android:padding="5dip"

                    ></TextView>

                <CheckBox
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="New CheckBox"
                    android:id="@+id/checkBox" />


            </LinearLayout >

        </FrameLayout>

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="6dp"
                android:layout_marginRight="6dp"
                android:layout_marginTop="4dp"
                android:layout_marginBottom="4dp"
                android:orientation="horizontal"
                android:background="@drawable/bg_card">

                <!-- Card Contents go here -->

                <Button
                    android:id="@+id/buttonAddList"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="Create List"

                    style="?android:attr/borderlessButtonStyle"
                    android:textColor="@color/orange"
                    android:textStyle="bold"
                    />




            </LinearLayout >

        </FrameLayout>







    </LinearLayout>

</ScrollView>

我目前在上面的代码中有一个复选框。我打算删除这个。该复选框只是为了显示我希望我的复选框出现的位置。

【问题讨论】:

    标签: java android checkbox android-checkbox


    【解决方案1】:

    您首先需要做的是向您的 LinearLayout(在该 XML 文件中)添加一个 id,该 ID 将用于保存 CheckBox。然后,在代码中,您需要通过其 id 获取该 LinearLayout 并使用 addView() 添加您动态创建的 CheckBoxes。我想在伪代码中它看起来像这样:

    for (int i = 0; i < numberOfCheckBoxes; i++) {
    
        CheckBox checkBox = new CheckBox();
        checkBox.setTitle("Your title");
        checkBox.setOnClickListener(new OnClickListener() {
    
            // Your code to be executed on click
        });
    
        linearLayout.addView(checkBox);
    }
    

    这有帮助吗?

    PS:如果你保持你的代码干净就好了 - ADT(我也相信 Eclipse)为你提供了 Shift+Ctrl+F 快捷方式来自动缩进你的代码 - 尽可能多地使用它;)

    【讨论】:

    • 我应该把 onclick 监听器扔到哪里?在我的异步任务结束时?
    • 我不知道该怎么回答;如果我能看到更多代码,也许我能做到,但我不能承诺任何事情。这里到底有什么问题?难道你不能在创建 CheckBox 对象实例时设置监听器,就像我提供的例子一样?
    【解决方案2】:

    由于您正在处理数据库项目,我建议使用 CursorAdapter 为您完成繁重的工作。 CursorAdapter 与任何 Adapter 类一样,可以处理数据库项并将它们定制到您选择的布局中,以便在 ListView 中使用。

    您必须对代码进行调整:

    • 创建一个布局文件,其中包含您要放入动态列表的任何内容。这是一个例子,假设它被命名为 list_contents.xml:

          <LinearLayout
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:layout_marginLeft="6dp"
              android:layout_marginRight="6dp"
              android:layout_marginTop="4dp"
              android:layout_marginBottom="4dp"
              android:orientation="vertical"
              android:background="@drawable/bg_card">
      
              <!-- Card Contents go here -->
      
      
              <TextView
                  android:id="@+id/styleDescription"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:ems="10"
                  android:textSize="15sp"
                  android:padding="5dip"
      
                  ></TextView>
      
              <CheckBox
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:text="New CheckBox"
                  android:id="@+id/checkBox" />
      
      
          </LinearLayout >
      
      </FrameLayout>
      
    • 然后,不要从 AsyncTask 返回列表,而是返回游标本身
      从您的数据库中。此 Cursor 将由 CursorAdapter 处理。我推荐这个指南:
      http://www.gustekdev.com/2013/05/custom-cursoradapter-and-why-not-use.html

    • 实现 CursorAdapter 方法:

    在您的 newView() 实现中,膨胀 list_contents.xml(请注意,如果您使用 ResourceCursorAdapter,则不需要这样做)

    在您的 CursorAdapter.bindView() 实现中执行以下操作:

    CheckBox checkbox = (CheckBox) view.findViewById(R.id.checkbox);
    checkbox.setText(cursor.getString(cursor.getColumnIndex(YOUR_DATABASE_COLUMN_NAME_FOR_CHECKBOX_VALUES)));
    checkbox.setOnCheckedChangedListener(listenerInitializedSomewhereFromFragmentCode);
    
    • 将您的 ScrollView 更改为 ListView(它可以在任何 Layout 中),并给它一个 id,比如 R.id.listview。

    • 最后,在您处理数据库中的列表的部分,我们现在有一个光标,只需这样做:

      CustomCursorAdapter cca = new CustomCursorAdapter(getActivity(), resultFromDatabase, 0); listView.setAdapter(cca);

    注意:getActivity() 用于在 Fragment 中工作时使用。它应该是一个上下文,所以在 Activity 中它可以只是“this”。

    注意2:此时listView应该已经通过findViewById初始化了。

    注意3:如果listView已经设置了Adapter和Cursor,你应该考虑调用listView.getAdapter().changeCursor()。

    【讨论】:

      【解决方案3】:

      Kotlin 中的简单代码

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

      handleCheck 方法

          private fun handleCheck(chk: CheckBox): CompoundButton.OnCheckedChangeListener? {
          return object : CompoundButton.OnCheckedChangeListener {
              override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
                  if (!isChecked) {
                      //uncheck
                  } else {
                      //check
                  }
              }
          }
      }
      

      你想做一些事情,直接使用 checkboxList 对象,比如 as

      val layout = findViewById<View>(R.id.layout_checkbox) as ViewGroup
          val ll = LinearLayout(this@MedicalHistoryActivity)
          ll.orientation = LinearLayout.VERTICAL
          for (i in 0 until health_status.size) {
              arr_cb[i]?.isEnabled = true
              // do something like change color or more
          }
          layout.addView(ll)
      

      用于启用复选框或更多。

      谢谢

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-02
        • 1970-01-01
        • 1970-01-01
        • 2019-07-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-26
        • 1970-01-01
        相关资源
        最近更新 更多