首页 > 解决方案 > 如何定义多个 sharedPreferences?

问题描述

我设法获得了 sharedPreferences 保存值。但我不知道如何让它引用我点击的文本。在// Close Alert Window我单击“确定”更改文本的部分中。Ok 关闭警报对话框,然后假设将新价格添加到列表中sharedPreferences

putString()如果我使用它,putString("Price$it", input.text.toString()).apply它似乎什么也没做。但是,如果我使用"Price1"任何我更改的文本,我会保存并在重新打开应用程序时Price1更改为新价格。所以我知道这个方法是有效的。我只是不知道如何保存我正在编辑的特定文本。我希望这是有道理的。谢谢你的时间。

// Created Private Price List
    val sharedPreferences = getSharedPreferences("priceList", Context.MODE_PRIVATE)

//Price
    (1..912).forEach {
        val id = resources.getIdentifier("Price$it", "id", packageName)
        val tv = findViewById<TextView>(id)
        tv.text = sharedPreferences.getString("Price$it","0.00")

    }

(1..912).forEach {
        val id = resources.getIdentifier("Price$it", "id", packageName)
        val tv = findViewById<TextView>(id)
        tv.setOnLongClickListener {

            //Alert Window
            val alertDialog = AlertDialog.Builder(this@MainActivity).create()
            alertDialog.setTitle("NEW PRICE")
            val input = EditText(this@MainActivity)
            //Alert Submit on Enter
            input.setOnKeyListener { v, keyCode, event ->
                if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
                    // Input changes text
                    tv.text = input.text
                    when {
                        tv.text.startsWith("-") -> tv.setTextColor(Color.RED)
                        tv.text.startsWith("+") -> tv.setTextColor(Color.GREEN)
                    else -> {
                        tv.text = "_"
                        tv.setTextColor(Color.DKGRAY)
                    }
                    }
                    // Close Alert Window
                    alertDialog.dismiss()
                    // TODO Save Price Table  //THIS PART vvv
                    sharedPreferences.edit().putString("Price1", input.text.toString()).apply()
                }
                false
            }


            val lp = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT
            )
            input.layoutParams = lp
            alertDialog.setView(input)
            alertDialog.show()
            return@setOnLongClickListener true

        }
    }

标签: stringforeachkotlinandroid-edittextsharedpreferences

解决方案


你在阴影it中。在您的范围内,您引用​​的是tv.setOnLongClickListener. 指定参数名称,使其不受内部 lambda 的影响。

(1..912).forEach { index ->
    ...
    sharedPreferences.edit().putString("Price$index", input.text.toString()).apply()
}    

推荐阅读