android - 按钮单击保存 sharedPreferences
问题描述
我正在尝试实现一个保存按钮,该按钮从几个 editText 输入中保存共享首选项。
我正在尝试实现一个按钮功能,当按下该按钮时,它会将来自多个 editTexts 的值保存到 sharedPreference 键中。经过一些研究,我将editText字段中的内容设置为变量,然后将其写入共享首选项。
fun onClick() {
var str = editText2.text.toString()
var dex = editText.text.toString()
var int = editText4.text.toString()
when () {
R.id.button -> {
//add write sharedPreferences
}
}
}
当我尝试在 when 括号中编译它时,我得到一个表达式错误。
解决方案
when
需要一个参数,该参数将与 case 等案例进行比较R.id.button
。
所以你可以像这样实现 onClickListener 接口
class MainActivity : AppCompatActivity(), View.OnClickListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//setSupportActionBar(findViewById(R.id.my_toolbar))
button.setOnClikListener(this)
fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return when (item.itemId) {
R.id.action_settings -> true
else -> super.onOptionsItemSelected(item)
}
}
override fun onClick(v: View?) {
var str = editText2.text.toString()
var dex = editText.text.toString()
var int = editText4.text.toString()
when (v.id) {
R.id.button -> {
//add write sharedPreferences
}
}
}
}
推荐阅读
- ios - Swift - 从 URL 下载图像后如何调整 UICollectionViewCells 的大小?
- python - 是否可以在 Python 中运行/启动沙盒 Lua 脚本?
- python - 文件路径未正确读取
- javascript - 切换用户可以删除文本框中的文本与不删除文本的状态
- open-source - ibm inforsphere cdc 开源解决方案
- python - 如何将 blob 复制到存储桶中的特定文件夹?
- docker - 本地主机上的 docker 容器存储
- laravel - Laravel Forge - 过去部署日志的完整列表
- ctypes - IronPyton ctypes union 失败并显示“SystemError:对象引用未设置为对象的实例”。
- visual-studio-code - Dart 使用 12 GB 内存运行