【发布时间】:2019-06-05 16:55:49
【问题描述】:
我已经设法获得 sharedPreferences 保存值。但我不知道如何让它引用我点击的文本。在// Close Alert Window 部分,当我单击确定更改文本时。确定关闭警报对话框,然后假设将新价格添加到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
}
}
【问题讨论】:
标签: string foreach kotlin android-edittext sharedpreferences