在活动之间切换时保存复选框状态(kotlin)

发布于 2025-02-09 01:51:03 字数 3992 浏览 2 评论 0原文

我正在Android Studio中为我的女友制作一个Android应用程序,以帮助她跟踪工作中的任务。该应用使用RecyClerview具有多个待办事项列表。由于每个清单都有自己的活动,并且她将在它们之间切换,因此我如何保存已检查哪些盒子,以便在活动之间切换时仍将检查它们?这是一个待办事项列表之一的RecyClerview适配器代码,其中还包含复选框代码。

package com.mattkalichman.coffee

import android.util.SparseBooleanArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.checkbox_row.view.*

class ThreeHourPullAdapter(var list: ArrayList<Data>) :
    RecyclerView.Adapter<ThreeHourPullAdapter.ViewHolder>() {

    private var titles =
        arrayOf(
            "Log into the handheld under Pull to Thaw.",
            "Count anything left on pastry cart (BOH).",
            "Count everything on front pastry cart (FOH).",
            "Put remaining pastries from BOH on FOH cart. Remember to FIFO!",
            "Pull from freezer to BOH cart. Adjust number of pulled items according to inventory.",
            "When pull is done, press complete pull at the bottom of the screen.",
            "Date all pastries with sticker gun by standards. (Marshmallow Dream Bars, Madelines, Chocolate Madelines, All Other Pastries)",
            "Make sure to hang sticker gun back on cart & plug handheld back in."
        )

    var checkBoxStateArray = SparseBooleanArray()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

        val context = parent.context
        val inflater = LayoutInflater.from(context)
        val view = inflater.inflate(R.layout.checkbox_row, parent, false)

        return ViewHolder(view)
    }

    override fun getItemCount(): Int = list.size

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

        holder.checkbox.isChecked = checkBoxStateArray.get(position, false)

        holder.checkbox.text = titles[position]

    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var checkbox: CheckBox = itemView.checkbox

        init {

            checkbox.setOnClickListener {
                if (!checkBoxStateArray.get(adapterPosition, false)) {
                    checkbox.isChecked = true
                    checkBoxStateArray.put(adapterPosition, true)
                } else {
                    checkbox.isChecked = false
                    checkBoxStateArray.put(adapterPosition, false)
                }

            }
        }
    }
}

编辑:我发现了!我将在此处发布代码,以防我遇到的问题相同,但是现在这部分效果很好:

inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var checkbox: CheckBox = itemView.checkbox

        var sharedPreferences: SharedPreferences =
            itemView.getContext().getSharedPreferences("ThreeHourPull", Context.MODE_PRIVATE) 
    // Create the SharedPreferences ^^^

        val editor: SharedPreferences.Editor = sharedPreferences.edit()
    // Create the editor ^^^

        init {
            for (i in 1..11) {
                checkBoxStateArray[i - 1] = 
                sharedPreferences.getBoolean("Checkbox" + i, false)
            } 
    // When launching the activity, the appropriate boxes will be checked ^^^

            checkbox.setOnClickListener {
                if (!checkBoxStateArray.get(adapterPosition, false)) {
                    checkbox.isChecked = true
                    checkBoxStateArray.put(adapterPosition, true)
                } else {
                    checkbox.isChecked = false
                    checkBoxStateArray.put(adapterPosition, false)
                }

                editor.apply { // Save the states of each checkbox in the SharedPreferences
                    for (i in 1..11) {
                        editor.putBoolean("Checkbox" + i, 
                        checkBoxStateArray[i - 1])
                    }
                    editor.apply()
                }
            }
        }
    }

I'm making an Android app in Android Studio for my girlfriend to help her keep track of her tasks at work. The app has multiple to-do lists using RecyclerView. Since each checklist has their own activity, and she will be switching between them, how do I save which boxes have been checked so that they remained checked when switching between activities? Here is the RecyclerView adapter code for one of the to-do lists that also contains the Checkbox code.

package com.mattkalichman.coffee

import android.util.SparseBooleanArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.checkbox_row.view.*

class ThreeHourPullAdapter(var list: ArrayList<Data>) :
    RecyclerView.Adapter<ThreeHourPullAdapter.ViewHolder>() {

    private var titles =
        arrayOf(
            "Log into the handheld under Pull to Thaw.",
            "Count anything left on pastry cart (BOH).",
            "Count everything on front pastry cart (FOH).",
            "Put remaining pastries from BOH on FOH cart. Remember to FIFO!",
            "Pull from freezer to BOH cart. Adjust number of pulled items according to inventory.",
            "When pull is done, press complete pull at the bottom of the screen.",
            "Date all pastries with sticker gun by standards. (Marshmallow Dream Bars, Madelines, Chocolate Madelines, All Other Pastries)",
            "Make sure to hang sticker gun back on cart & plug handheld back in."
        )

    var checkBoxStateArray = SparseBooleanArray()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

        val context = parent.context
        val inflater = LayoutInflater.from(context)
        val view = inflater.inflate(R.layout.checkbox_row, parent, false)

        return ViewHolder(view)
    }

    override fun getItemCount(): Int = list.size

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

        holder.checkbox.isChecked = checkBoxStateArray.get(position, false)

        holder.checkbox.text = titles[position]

    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var checkbox: CheckBox = itemView.checkbox

        init {

            checkbox.setOnClickListener {
                if (!checkBoxStateArray.get(adapterPosition, false)) {
                    checkbox.isChecked = true
                    checkBoxStateArray.put(adapterPosition, true)
                } else {
                    checkbox.isChecked = false
                    checkBoxStateArray.put(adapterPosition, false)
                }

            }
        }
    }
}

Edit: I FIGURED IT OUT!! I'll post the code here in case anyone has the same problem I did, but this portion works perfectly now:

inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var checkbox: CheckBox = itemView.checkbox

        var sharedPreferences: SharedPreferences =
            itemView.getContext().getSharedPreferences("ThreeHourPull", Context.MODE_PRIVATE) 
    // Create the SharedPreferences ^^^

        val editor: SharedPreferences.Editor = sharedPreferences.edit()
    // Create the editor ^^^

        init {
            for (i in 1..11) {
                checkBoxStateArray[i - 1] = 
                sharedPreferences.getBoolean("Checkbox" + i, false)
            } 
    // When launching the activity, the appropriate boxes will be checked ^^^

            checkbox.setOnClickListener {
                if (!checkBoxStateArray.get(adapterPosition, false)) {
                    checkbox.isChecked = true
                    checkBoxStateArray.put(adapterPosition, true)
                } else {
                    checkbox.isChecked = false
                    checkBoxStateArray.put(adapterPosition, false)
                }

                editor.apply { // Save the states of each checkbox in the SharedPreferences
                    for (i in 1..11) {
                        editor.putBoolean("Checkbox" + i, 
                        checkBoxStateArray[i - 1])
                    }
                    editor.apply()
                }
            }
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

绝情姑娘 2025-02-16 01:51:03

您需要以某种方式坚持这些数据,并在活动启动时恢复数据。有很多方法可以做到 - 现代方法将是viewmodel处理内部状态(列表项目以及是否已检查)并将其推向UI层(片段,设置,这些项目在适配器上)。每当您选中一个框时,该事件都会发送到VM,以便它可以更新“检查的内容”状态,并将其保存到数据库,sharedPreferencesdatastore etceet 。

​将它们存储在onStop之类的东西中,并在设置过程中还原它们,当您向适配器提供数据时。我已经写了一个关于此

You'll need to persist that data somehow, and restore it when the activity starts. There's lots of ways to do it - a modern approach would be something like a ViewModel handling the internal state (list items and whether they're checked) and pushing that to the UI layer (the fragment, setting those items on the adapter). And whenever you check a box, that event is sent to the VM so it can update the "what's checked" state, and save it to a database, SharedPreferences, DataStore etc.

But if you want to keep it simple, you could just use SharedPreferences and serialise the indices of the checked items. Store them in something like onStop, and restore them during setup, when you're providing data to the adapter. I already wrote an answer about this so I'll just link that, but if there's anything you're not sure of you can just ask here!

↙温凉少女 2025-02-16 01:51:03

您可以使用共享Preferences或SQLITE数据库。

您也可以只使用已检查所有ID的Singleton对象类(静态对象)。

如何在Kotlin中声明Singleton

,或者您还可以使用意见来通过活动之间的检查ID。

或者,您可以使用livedata:

链接

You can use SharedPreferences or the SQLite database.

You can also just use a Singleton object class (a static object) with all the ids checked.

HOW TO DECLARE SINGLETON IN KOTLIN

Or you can also pass the checked ids between activities using Intents.

Or you can use LiveData:

LINK

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文