具有onclick函数的动态复选框列表

时间:2014-03-26 20:28:36

标签: java android checkbox android-checkbox

我有一个页面,它返回数据库中的项目列表。我想通过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>

我目前在上面的代码中有一个复选框。我计划删除它。该复选框只是为了显示我希望我的复选框显示在哪里。

3 个答案:

答案 0 :(得分:2)

首先需要做的是为您的LinearLayout(在该XML文件中)添加一个id,它将保存CheckBoxes。然后,在代码中,您需要通过其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快捷键来自动缩进你的代码 - 尽可能经常使用它;)

答案 1 :(得分:0)

由于您正在处理数据库项目,我建议您使用CursorAdapter为您完成繁重的工作。与任何Adapter类一样,CursorAdapter可以处理数据库项并将它们自定义为您选择的布局,以便在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返回List,而是返回Cursor本身 来自您的数据库。 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(可以在任何布局中),并为其指定一个ID,例如R.id.listview。

  • 最后,在您从数据库处理List的部分中,我们现在有了一个Cursor,只需执行此操作:

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

注意:getActivity()适用于在Fragment中工作的情况。它应该是一个上下文,所以在一个Activity中它可以只是&#34;这个&#34;。

注2:此时应通过findViewById初始化listView。

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

答案 2 :(得分:0)

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 对象做一些事情,例如

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)

用于启用复选框或更多。

谢谢

相关问题