【发布时间】:2019-05-20 20:12:09
【问题描述】:
我正在构建函数以将变量从 editText 字段写入 sharedPreferences。
我尝试了几种写入 sharedPreferences 的可能性,但都没有奏效,因此决定自己编写。因此,我将相关的 TextView 字段设置为 onClick'able,然后运行写入 sharedPreferences 函数。
package com.taylorworld.tw01
import android.content.Context
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity;
import android.view.Menu
import android.view.MenuItem
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
class MainActivity() : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//setSupportActionBar(findViewById(R.id.my_toolbar))
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)
}
}
var strength = editText2.text.toString()
var dexterity = editText.text.toString()
var intelligance = editText4.text.toString()
var wisdom = editText3.text.toString()
var constitution = editText6.text.toString()
var charisma = editText5.text.toString()
var chrname = editText7.text.toString()
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE)
public fun saveStr(view: View) {
val sharedPref = activity?.setPreferences(Context.MODE_PRIVATE) ?: return with(sharedPref.edit()) {
putInt(getString(STR), strength)
commit()
}
}
public fun saveDex(view: View) {
val sharedPref = activity?.setPreferences(Context.MODE_PRIVATE) ?: return with(sharedPref.edit()) {
putInt(getString(DEX), dexterity)
commit()
}
}
public fun readStr(view: View) {
}
}
我从第 50、54 和 62 行收到“未解决的参考:活动”错误,但不知道如何解决这些错误。
【问题讨论】:
-
欢迎来到 Stack Overflow!这里没有行号,50、54和62在哪里?你得到了哪些错误?您尝试了哪些“几种可能性”?也请take the tour 和阅读"How do I ask a good question?" 当你有空的时候,它会让我们更容易帮助你。
-
谢谢。这些行号包含, val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) val sharedPref = activity?.setPreferences(Context.MODE_PRIVATE) ?: return 和 val sharedPref = activity?.setPreferences(Context.MODE_PRIVATE) ?: return 。我从上面发布的 MainActivity.kt 中的这三行中得到了“未解决的参考:活动”错误。我的 git repo 提交说得很好,在我试图实现它的代码中,即我尝试过的那些可能性。
标签: android kotlin sharedpreferences