【发布时间】:2018-10-21 19:11:09
【问题描述】:
我试图在 kotlin 中的两个活动之间传递一个值,但如果我使用下面的代码,那么我只会得到“Hello World”默认值,而不是 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)
}
}
【问题讨论】:
-
在 kotlin 中我们可以使用不同的方法。更多详情请看这里:stackoverflow.com/a/56873719/3710341