samedi 4 février 2023

Save MutableListOf

I have a problem and I don't know how I could create a function to save the state of a MutableListOf when the application is closed and another one to restore it when it is opened again. Could someone help me?

Code: class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    val button = findViewById<Button>(R.id.button)
    val text = findViewById<TextView>(R.id.editTextTextPersonName)
    val layout = findViewById<ConstraintLayout>(R.id.layout)
    var numbers = 0
    var checkboxes = mutableListOf<CheckBox>()
    
    button.setOnClickListener {
        val checkbox = CheckBox(this)
        checkbox.text = text.text
        text.text = ""
        checkbox.textSize = 13f
        val font = Typeface.create(Typeface.MONOSPACE, Typeface.BOLD)
        checkbox.typeface = font
        layout.addView(checkbox)
        val params = ConstraintLayout.LayoutParams(
            ConstraintLayout.LayoutParams.WRAP_CONTENT,
            ConstraintLayout.LayoutParams.WRAP_CONTENT
        )
        params.setMargins(100, numbers * 75, 100, 100)
        params.width = 1020
        params.height = 120
        checkbox.layoutParams = params
        checkbox.id = View.generateViewId()
        val constraintSet = ConstraintSet()
        constraintSet.clone(layout)
        constraintSet.connect(
            checkbox.id,
            ConstraintSet.TOP,
            layout.id,
            ConstraintSet.TOP,
            numbers * 75
        )
        constraintSet.connect(
            checkbox.id,
            ConstraintSet.START,
            layout.id,
            ConstraintSet.START,
            0
        )
        constraintSet.applyTo(layout)
        numbers += 1
        checkboxes.add(checkbox)
        checkbox.setOnClickListener {
            checkbox.animate().alpha(1f).withEndAction {
                checkbox.isChecked = false
                layout.removeView(checkbox)
                numbers -= 1
                checkboxes.remove(checkbox)
                checkboxes.forEachIndexed { index, cb ->
                    val params = cb.layoutParams as ConstraintLayout.LayoutParams
                    params.setMargins(0, index * 75, 0, 0)
                    cb.layoutParams = params
                    val constraintSet = ConstraintSet()
                    constraintSet.clone(layout)
                    constraintSet.connect(
                        cb.id,
                        ConstraintSet.TOP,
                        layout.id,
                        ConstraintSet.TOP,
                        index * 75
                    )
                    constraintSet.applyTo(layout)
                }
            }.start()
        }
    }
}

}

I have tried many things but none of them have worked




Aucun commentaire:

Enregistrer un commentaire