如何在android kotlin中使用一个复选框选择多个复选框?

2024-01-27

这是我的活动代码:-

class SelectCoursesActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_select_courses)

        all_courses.setOnCheckedChangeListener { _, _ ->
            if (all_courses.isChecked) {
                scienceCourses()
                artsCourses()
                commerceCourses()
                all_science.isChecked = true
                all_arts.isChecked = true
                all_commerce.isChecked = true
            } else {
                scienceCourses()
                artsCourses()
                commerceCourses()
                all_science.isChecked = false
                all_arts.isChecked = false
                all_commerce.isChecked = false
            }
        }


        all_science.setOnCheckedChangeListener { _, _ ->
            all_courses.isChecked =
                all_science.isChecked && all_arts.isChecked && all_commerce.isChecked
        }

        all_arts.setOnCheckedChangeListener { _, _ ->
            all_courses.isChecked =
                all_science.isChecked && all_arts.isChecked && all_commerce.isChecked
        }

        all_commerce.setOnCheckedChangeListener { _, _ ->
            all_courses.isChecked =
                all_science.isChecked && all_arts.isChecked && all_commerce.isChecked
        }
    }

    private fun commerceCourses() {
        all_commerce.setOnCheckedChangeListener { _, _ ->
            if (all_commerce.isChecked) {
                accountancy.isChecked = true
                businessStudies.isChecked = true
                physicalEducation.isChecked = true
            } else {
                accountancy.isChecked = false
                businessStudies.isChecked = false
                physicalEducation.isChecked = false
            }
        }

        accountancy.setOnCheckedChangeListener { _, _ ->
            all_commerce.isChecked =
                accountancy.isChecked && businessStudies.isChecked && physicalEducation.isChecked
        }

        businessStudies.setOnCheckedChangeListener { _, _ ->
            all_commerce.isChecked =
                accountancy.isChecked && businessStudies.isChecked && physicalEducation.isChecked
        }

        physicalEducation.setOnCheckedChangeListener { _, _ ->
            all_commerce.isChecked =
                accountancy.isChecked && businessStudies.isChecked && physicalEducation.isChecked
        }
    }

    private fun artsCourses() {
        all_arts.setOnCheckedChangeListener { _, _ ->
            if (all_arts.isChecked) {
                economics.isChecked = true
                history.isChecked = true
                politicalScience.isChecked = true
            } else {
                economics.isChecked = false
                history.isChecked = false
                politicalScience.isChecked = false
            }
        }

        economics.setOnCheckedChangeListener { _, _ ->
            all_arts.isChecked =
                economics.isChecked && history.isChecked && politicalScience.isChecked
        }

        history.setOnCheckedChangeListener { _, _ ->
            all_arts.isChecked =
                economics.isChecked && history.isChecked && politicalScience.isChecked
        }

        politicalScience.setOnCheckedChangeListener { _, _ ->
            all_arts.isChecked =
                economics.isChecked && history.isChecked && politicalScience.isChecked
        }
    }

    private fun scienceCourses() {
        all_science.setOnCheckedChangeListener { _, _ ->
            if (all_science.isChecked) {
                physics.isChecked = true
                chemistry.isChecked = true
                math.isChecked = true
            } else {
                physics.isChecked = false
                chemistry.isChecked = false
                math.isChecked = false
            }
        }

        physics.setOnCheckedChangeListener { _, _ ->
            all_science.isChecked = physics.isChecked && chemistry.isChecked && math.isChecked
        }

        chemistry.setOnCheckedChangeListener { _, _ ->
            all_science.isChecked = physics.isChecked && chemistry.isChecked && math.isChecked
        }

        math.setOnCheckedChangeListener { _, _ ->
            all_science.isChecked = physics.isChecked && chemistry.isChecked && math.isChecked
        }
    }
}

这是活动 xml 代码:-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_margin="20dp"
    tools:context=".SelectCoursesActivity">

    <CheckBox
        android:id="@+id/all_courses"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/all_courses"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/science"
        android:textSize="20sp"
        android:textStyle="bold"/>

    <CheckBox
        android:id="@+id/all_science"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/all"/>

    <CheckBox
        android:id="@+id/physics"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/physics"/>

    <CheckBox
        android:id="@+id/math"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/math"/>

    <CheckBox
        android:id="@+id/chemistry"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/chemistry"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/arts"
        android:textSize="20sp"
        android:textStyle="bold"/>

    <CheckBox
        android:id="@+id/all_arts"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/all"/>

    <CheckBox
        android:id="@+id/economics"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/economics"/>

    <CheckBox
        android:id="@+id/history"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/history"/>

    <CheckBox
        android:id="@+id/politicalScience"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/politicalScience"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/science"
        android:textSize="20sp"
        android:textStyle="bold"/>

    <CheckBox
        android:id="@+id/all_commerce"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/all"/>

    <CheckBox
        android:id="@+id/accountancy"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/accountancy"/>

    <CheckBox
        android:id="@+id/businessStudies"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/businessStudies"/>

    <CheckBox
        android:id="@+id/physicalEducation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/physicalEducation"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:backgroundTint="@null"
        android:background="@drawable/circular_button"
        android:textColor="@color/red_primary"
        android:text="@string/save"/>

</LinearLayout>

我正在尝试进行活动,如果:- 1) 选中所有课程复选框,然后应选中所有其他复选框,反之亦然。

2)选中所有科学按钮,然后应选择所有其他学科按钮,反之亦然。所有其他科目也一样。

3)如果任何课程按钮未被选中,则所有课程按钮也不应被选中。所有科目也一样。

现在我可以使用所有课程按钮检查和取消选中。但是,当我取消选中任何课程按钮时,我并不是取消选中所有课程按钮。

当选中任何课程按钮并且取消选中任何主题时,它会取消选中该课程中的所有主题。我只想取消选中该课程复选框,并且所有其他课程都应保持选中状态。


以这种方式使用 recyclerView 而不是直接复选框:-

活动代码:-

lateinit var recyclerView: RecyclerView
lateinit var adapter: CheckboxAdapter
lateinit var list3: List<RowModel>
lateinit var list1: List<RowModel>
lateinit var list2: List<RowModel>
lateinit var list4: List<RowModel>
lateinit var list: List<RowModel>

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_select_courses)

    recyclerView = findViewById(R.id.trail_rv)

    list1 = listOf(
        RowModel(RowType.TopHeader, "", "", "", false)
    )

    list2 = listOf(
        RowModel(RowType.Course, "", "", "Science", false),
        RowModel(RowType.SubjectRow, "Physics", "", "Science", false),
        RowModel(RowType.Dummy, "Physics", "Physics", "Science", false),
        RowModel(RowType.SubjectRow, "Math", "", "Science", false),
        RowModel(RowType.Dummy, "Math", "Math", "Science", false),
        RowModel(RowType.SubjectRow, "Chemistry", "", "Science", false),
        RowModel(RowType.Dummy, "Chemistry", "Chemistry", "Science", false)
    )

    list3 = listOf(
        RowModel(RowType.Course, "", "", "Arts", false),
        RowModel(RowType.SubjectRow, "Economics", "", "Arts", false),
        RowModel(RowType.Dummy, "Economics", "Economics", "Arts", false),
        RowModel(RowType.SubjectRow, "History", "", "Arts", false),
        RowModel(RowType.Dummy, "History", "History", "Arts", false),
        RowModel(RowType.SubjectRow, "Political Science", "", "Arts", false),
        RowModel(RowType.Dummy, "Political Science", "Political Science", "Arts", false)
    )

    list4 = listOf(
        RowModel(RowType.Course, "", "", "Commerce", false),
        RowModel(RowType.SubjectRow, "Accountancy", "", "Commerce", false),
        RowModel(RowType.Dummy, "Accountancy", "Accountancy", "Commerce", false),
        RowModel(RowType.SubjectRow, "Business Studies", "", "Commerce", false),
        RowModel(RowType.Dummy, "Business Studies", "Business Studies", "Commerce", false),
        RowModel(RowType.SubjectRow, "Physical Education", "", "Commerce", false),
        RowModel(RowType.Dummy, "Physical Education", "Physical Education", "Commerce", false)
    )

    list = list1 + list2 + list4 + list3

    adapter = CheckboxAdapter(this, list)
    adapter.setList(list)
    recyclerView.adapter = adapter
    recyclerView.layoutManager = LinearLayoutManager(this)

    findViewById<Button>(R.id.showTextBtn).setOnClickListener {
        val checkboxesValue: String = selectedCheckboxes.joinToString(separator = ";\n")
        findViewById<TextView>(R.id.ShowTextView).text = checkboxesValue
    }

    findViewById<Button>(R.id.clearTextBtn).setOnClickListener {
        selectedCheckboxes.clear()
        adapter.setList(list)
    }

    }
}

适配器代码:-

class CheckboxAdapter(
    private val context: Context,
    var productList: List<RowModel>,
) : RecyclerView.Adapter<CheckboxAdapter.TableViewHolder>() {


    override fun onBindViewHolder(holder: TableViewHolder, position: Int) {

        val item = productList[position]

        holder.checkBox.setOnCheckedChangeListener(null)
        holder.checkBox.isChecked = item.isChecked

        val params: ViewGroup.MarginLayoutParams =
            holder.checkBox.layoutParams as ViewGroup.MarginLayoutParams

        when (item.rowType) {
            RowType.TopHeader -> {
                holder.checkBox.text = "All Courses"
                holder.checkBox.visibility = View.VISIBLE
                holder.checkBox.typeface = Typeface.DEFAULT_BOLD
                params.setMargins(0, 0, 0, 0)
                holder.checkBox.layoutParams = params

            }
            RowType.Course -> {

                holder.checkBox.visibility = View.VISIBLE
                holder.checkBox.text = item.course
                holder.checkBox.typeface = Typeface.DEFAULT_BOLD
                params.setMargins(20, 0, 0, 0)
                holder.checkBox.layoutParams = params

            }
            RowType.SubjectRow -> {

                holder.checkBox.visibility = View.VISIBLE
                holder.checkBox.text = item.subjectName
                holder.checkBox.typeface = Typeface.DEFAULT
                params.setMargins(convertDpToPixel(40f, context).toInt(), 0, 0, 0)
                holder.checkBox.layoutParams = params
            }
            RowType.Dummy -> {

                holder.checkBox.visibility = View.GONE
                holder.checkBox.text = item.subjectName
                holder.checkBox.typeface = Typeface.DEFAULT
                params.setMargins(convertDpToPixel(60f, context).toInt(), 0, 0, 0)
                holder.checkBox.layoutParams = params
            }
        }

        holder.checkBox.setOnCheckedChangeListener { _, isChecked ->
            if (item.isChecked != isChecked) {
                item.isChecked = isChecked

                when (item.rowType) {
                    RowType.TopHeader -> {
                        val indexList = mutableListOf<Int>()
                        productList.filter { it.rowType != RowType.TopHeader }.forEach {
                            it.isChecked = isChecked
                            indexList.add(productList.indexOf(it))
                        }
                        indexList.forEach {
                            notifyItemChanged(it)
                        }
                    }
                    RowType.Course -> {
                        val indexList = mutableListOf<Int>()
                        productList.filter { it.rowType == RowType.SubjectRow && it.course == item.course }
                            .forEach {
                                it.isChecked = isChecked
                                indexList.add(productList.indexOf(it))
                            }
                        productList.filter { it.rowType == RowType.Dummy && it.course == item.course }
                            .forEach {
                                it.isChecked = isChecked
                                indexList.add(productList.indexOf(it))
                            }
                        indexList.forEach {
                            notifyItemChanged(it)
                        }
                        isAllItemsSameStatus() //for header
                    }
                    RowType.SubjectRow -> {
                        val indexList = mutableListOf<Int>()
                        productList.filter { it.rowType == RowType.Dummy && it.subjectName == item.subjectName }
                            .forEach {
                                it.isChecked = isChecked
                                indexList.add(productList.indexOf(it))
                            }
                        indexList.forEach {
                            notifyItemChanged(it)
                        }
                        isAllItemsSameStatus()
                    }
                }
            }
        }


        when (item.rowType) {
            RowType.Course -> {
                if (holder.checkBox.isChecked)
                    selectedCheckboxes.add(holder.checkBox.text.toString())
                if (!holder.checkBox.isChecked) {
                    selectedCheckboxes.remove(holder.checkBox.text.toString())
                }
            }
            RowType.Dummy -> {
                if (holder.checkBox.isChecked)
                    selectedCheckboxes.add(holder.checkBox.text.toString())
                if (!holder.checkBox.isChecked) {
                    selectedCheckboxes.remove(holder.checkBox.text.toString())
                }
            }
        }
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TableViewHolder {
        return TableViewHolder(
            LayoutInflater.from(context).inflate(
                R.layout.checkbox,
                parent,
                false
            )
        )
    }

    class TableViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        val checkBox: CheckBox = itemView.findViewById(R.id.Checkbox)

    }

    override fun getItemCount() = productList.size


    fun setList(profiles: List<RowModel>) {
        productList = profiles
        notifyDataSetChanged()
    }

    private fun isAllItemsSameStatus(cat: String? = null) {

        val row: RowModel
        var isChecked: Boolean = true
        var position: Int = 0

        if (cat != null) {
            val catRow = productList.find { it.rowType == RowType.Course && it.course == cat }
            catRow?.let {
                val subList =
                    productList.filter { it.course == it.course && it.rowType == RowType.SubjectRow }
                isChecked = subList.filter { it.isChecked }.size == subList.size
                position = productList.indexOf(catRow)
            }
            if (catRow == null)
                return
            else
                row = catRow
        } else {
            row = productList[0]
            isChecked =
                productList.filter { it.rowType != RowType.TopHeader && it.isChecked }.size == productList.size - 1
            position = 0
        }

        updateHeader(row, isChecked, position)
    }

    private fun isAllSubjectItemsSameStatus(cat: String? = null) {

        val row: RowModel
        var isChecked: Boolean = true
        var position: Int = 0

        if (cat != null) {
            val catRow =
                productList.find { it.rowType == RowType.SubjectRow && it.subjectName == cat }
            catRow?.let {
                val subList =
                    productList.filter { it.subjectName == it.subjectName && it.rowType == RowType.Dummy }
                isChecked = subList.filter { it.isChecked }.size == subList.size
                position = productList.indexOf(catRow)
            }
            if (catRow == null)
                return
            else
                row = catRow
        } else {
            row = productList[0]
            isChecked =
                productList.filter { it.rowType != RowType.TopHeader && it.isChecked }.size == productList.size - 1
            position = 0
        }

        updateHeader(row, isChecked, position)
    }


    private fun updateHeader(item: RowModel, isChecked: Boolean, position: Int) {
        if (item.isChecked != isChecked) // no need to update if no change
        {
            item.isChecked = isChecked
            notifyItemChanged(position)

        }
    }

    private fun convertDpToPixel(dp: Float, context: Context): Float {
        return dp * (context.resources
            .displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
    }

    companion object {
        var selectedCheckboxes: ArrayList<String> = ArrayList()
    }

}

模型数据类代码:-

data class SubjectRowModel (
    val SubjectRowType: SubjectRowType,
    val subjectName: String,
    val dummyName: String,
    val course: String,
    var isChecked: Boolean = true)

enum class SubjectRowType(val id : Int) {

    TopHeader(1),
    Course(2),
    SubjectRow(3),
    Dummy(4);

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在android kotlin中使用一个复选框选择多个复选框? 的相关文章

随机推荐

  • Websocket 因 1006 错误而断开连接,无原因

    我正在我的网页游戏中记录断开连接 似乎 75 的会话因代码 1001 正常 而断开连接 25 的会话因代码 1006 错误 而断开连接 https www rfc editor org rfc rfc6455 https www rfc e
  • 五个不同的 GAE 站点可以共享一个公共数据存储吗?

    除了特定站点的数据存储之外 您是否还可以在所有网站之间共享一个数据存储 比如连接到与主 MySQL 数据库不同的 MySQL 数据库 并不真地 两种解决方法 使用同一应用程序的五个 版本 而不是五个不同的应用程序 他们将共享相同的数据存储
  • 将 python django 项目 1.3 升级到 1.5

    目前我有一个使用 django 版本 1 3 的 python 项目在 Mountain Lion OS 上运行 现在我想将其升级到 django 1 5 但是当我把它放在尝试做的时候python manage py runserver我收
  • 具有 SFINAE 虚拟参数的不明确模板

    考虑一种需要验证类型的情况T与另一个模板g 可能是一些enable if表达式 例如 在另一个模板的虚拟参数内 如下所示 template
  • ConnectionString 属性尚未初始化

    我查看了不同论坛上的很多帖子 其他人也收到了同样的错误 大多数人表示他们没有正确引用 web config 文件中的连接字符串 或者他们在设置连接字符串之前尝试打开连接 好吧 如果对我来说是这种情况 那么它如何在两个不同的系统上工作 但在第
  • 如何在 CertCreate 自签名证书函数中指定密钥大小

    我正在使用该功能证书创建自签名证书 https msdn microsoft com en us library windows desktop aa376039 v vs 85 aspx生成证书 我需要指定密钥大小2048 我不知道如何提
  • javascript按索引号进行字符串分配怪癖

    a 12345 a 2 3 a 2 9 console log a gt 12345 到底是怎么回事 这个怪癖导致我痛苦地调试了1个小时 如何以明智的方式避免这种情况 不能使用方括号重写字符串中的各个字符 仅 getter 即读取 访问可用
  • Github 操作 `on` 中没有定义事件触发器

    我创建了一个管道 我想在每次推送任何分支时触发 有我的default yml name default on push branches jobs build runs on macOS latest steps uses actions
  • 模板类的 typedef?

    是否有可能typedef使用模板的长类型 例如 template
  • 反应本机要求不适用于图像源

    给出下面的代码 反应本机抱怨 Requiring unknown module images Foo png If you are sure the module is there try restarting the packager o
  • 在 Android 中使用 OpenCV 检测图像中的圆圈

    我正在开发一个安卓应用程序其中我必须检测现有图像上的圆圈 从图库浏览或从相机捕获 浏览 捕获的图像将显示在 ImageView 上 顺便说一句 我正在使用OpenCV Android 库我正确地编译了它 对我的 Android 应用程序有任
  • 我可以同时使用 SOAP Webservices 和 Spring MVC

    我有一个 Spring MVC 项目 我写了一段类似的代码 Controller RequestMapping CallBack WebService name NotificationToCP targetNamespace http S
  • 当列不存在时 Postgres 返回默认值

    我有一个查询 如果缺少某个列 我本质上需要一个后备值 我想知道我是否可以纯粹在查询中处理这个问题 而不是先探测并发送单独的查询 本质上我正在寻找相当于COALESCE处理缺失列的情况 想象一下以下两张表 T1 id title extra
  • Visibility.Hidden 状态的解决方法 - Windows Phone 8.1 应用程序开发

    我无法将进度条的可见性状态指定为隐藏 我读过 在 WPF 模型中 隐藏表示对象不应呈现的可见状态 但仍应占用 WPF 布局中的空间 Silverlight 不支持隐藏 是否有解决方法可以达到与我的应用程序中隐藏相同的效果 Visibilit
  • Beaglebone GPIO 输入不起作用

    我正在使用 beaglebone 通过 sysfs 接口访问特定引脚的数字输入 我可以更改输出状态 但不能更改输入 我所做的是 我有两个引脚 pinA 和 pinB pinA 我将其输出 pinB 我将其输入 将 pinA 连接到 pinB
  • 这个标准化功能如何工作?

    我正在做 Junit 教程 遇到了正在测试的标准化函数 它的定义如下 public static String normalizeWord String word try int i Class normalizerFormClass nu
  • 如何获取运行 C# 应用程序的服务器的 IP 地址?

    我正在运行一个服务器 我想显示我自己的IP地址 获取计算机自己 如果可能的话 外部 IP 地址的语法是什么 有人写了下面的代码 IPHostEntry host string localIP host Dns GetHostEntry Dn
  • 在 FakeRequest 中使用 MultipartFormData 进行框架测试

    我目前正在为 Play Framework 2 2 x 应用程序编写一些 Specs2 测试 该应用程序接受 MultipartFormData 提交作为其功能的一部分 我已经使用以下形式成功地使用文本和 JSON 主体编写了其他测试 re
  • 在 GHCi 中定义函数签名

    在 Haskell 的解释器 GHCi 中定义函数签名不起作用 复制一个例子这一页 https wiki haskell org Function Prelude gt square Int gt Int
  • 如何在android kotlin中使用一个复选框选择多个复选框?

    这是我的活动代码 class SelectCoursesActivity AppCompatActivity override fun onCreate savedInstanceState Bundle super onCreate sa