首页 > 解决方案 > 按钮单击保存 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 括号中编译它时,我得到一个表达式错误。

标签: androidkotlinmain-activity

解决方案


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
            }
        }
    }
}

推荐阅读