string - 如何定义多个 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
}
}
解决方案
你在阴影it
中。在您的范围内,您引用的是tv.setOnLongClickListener
. 指定参数名称,使其不受内部 lambda 的影响。
(1..912).forEach { index ->
...
sharedPreferences.edit().putString("Price$index", input.text.toString()).apply()
}
推荐阅读
- python - 从 .jpg 图像转换回 2D numpy 数组
- azure-functions - 是否可以按随机时间表触发 azure 功能?
- python-3.x - 对类属性使用 side_effect 不起作用
- javascript - 如何在 React Redux 中获取状态的先前值
- postgresql - PostgreSQL 保留任何复制槽都不需要的 WAL 段
- python - 在 Python OOP 中声明全局变量并跨方法传递值
- javascript - 浏览器关闭和标签关闭标识符
- javascript - Node JS + Express:错误对象未在 Promise 中被拒绝
- javascript - 单选按钮在javascript中返回未定义的值
- android - 使用 Room 从单个事务中的多个表中获取数据?