我试图在kotlin中的两个活动之间传递一个值,但是如果我使用下面的代码,那么我只得到"Hello“默认值,而不是PREFERENCE_NAME值。我的文本id名是android:id="@+id/tv_count“--任何帮助都是非常感谢的。
Main Activity:
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val mypreference=MyPreference(this)
var loginCount=mypreference.getLoginName()
mypreference.setLoginName(loginCount)
tv_count.text=loginCount.toString()
}
}
My Preference:
import android.content.Context
class MyPreference(context:Context)
{
val PREFERENCE_NAME="SharedPreferenceExample"
val preference=context.getSharedPreferences(PREFERENCE_NAME,Context.MODE_PRIVATE)
fun getLoginName():String
{
return preference.getString(PREFERENCE_NAME,"Hello World")
}
fun setLoginName(name:String)
{
val editor=preference.edit()
editor.putString(PREFERENCE_NAME,name)
}
}发布于 2018-10-21 19:48:58
您需要调用commit,即
fun setLoginName(name:String)
{
val editor=preference.edit()
editor.putString(PREFERENCE_NAME,name)
editor.commit()
}发布于 2018-12-27 10:02:36
在您的示例中,您没有使用editor.commit()函数。这是整个代码
//Store in SharedPreference
val preference=getSharedPreferences(resources.getString(R.string.app_name), Context.MODE_PRIVATE)
val editor=preference.edit()
editor.putBoolean("isLoggedIn",true)
editor.putInt("id",1)
editor.putString("name","Alex")
editor.commit()
//Retrieve from SharedPreference
val name= preference.getString("name","")
val id= preference.getInt("id",0)
val isLoggedIn= preference.getBoolean("isLoggedIn",false)发布于 2019-06-27 12:51:50
这将是一个更广泛的答案,展示了一种非常优雅地使用首选项的一般方法,这要感谢Kotlin中的委托属性。这使我们能够为日常财产提供我们自己的后盾。
考虑一下这个类,它描述了如何读取和写入布尔值:
class BooleanPrefStore(val default: Boolean = false) {
operator fun getValue(thisRef: ContextWrapper?, property: KProperty<*>): Boolean =
PreferenceManager.getDefaultSharedPreferences(thisRef)
.getBoolean(property.name, default)
operator fun setValue(thisRef: ContextWrapper?, property: KProperty<*>, value: Boolean) {
PreferenceManager.getDefaultSharedPreferences(thisRef)
.edit()
.putBoolean(property.name, value)
.apply()
}
}一种getter和setter,它们使用通常的方式从首选项中读取和写入。通过这个类,我们可以非常简洁和优雅地设置我们的属性:
var Property1: Boolean by BooleanPrefStore()
var Property2: Boolean by BooleanPrefStore(true)它甚至允许我们提供一个默认值,如果它不同于“缺省值”。如果需要的话,只需以相同的方式创建其他帮助类,IntPrefStore、LongPrefStore或StringPrefStore。然后,您只需使用这些属性或为它们赋值,所有属性都将自动存储到首选项存储中并从首选项存储中检索。
请注意:首选项存储需要访问当前上下文。如果在保留上下文的Activity、Fragment或类似的Android类中声明这些属性,则没有其他事情可做。所有这些类都实现了ContextWrapper。但是,如果您需要您自己的类中的属性,则需要自己将其设置为ContextWrapper,例如:
class MyClass private constructor(context: Context) : ContextWrapper(context) {
...只需在实例化它时提供上下文即可。
https://stackoverflow.com/questions/52918895
复制相似问题