退出应用程序时保存变量
我对 Android Studio 很陌生(我昨天才开始),我正在编写一种点击游戏(用 XML 和 kotlin 编写)。 我希望点击计数器(位于文本视图中,开头有文本)在离开应用程序时保存并在启动时加载。我查了 savepreferences 但我不太明白它是如何工作的..你们能帮我吗?
`class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val one:ImageButton = findViewById<ImageButton>(R.id.iv_image)
val mp: MediaPlayer = MediaPlayer.create(this, R.raw.click)
var mCounter = 0
var txv = findViewById<TextView>(R.id.tx)
one.setOnClickListener {
//Play sound when click
mp.start()
//Increment click counter
mCounter++
txv.text = "Fixed mistakes: " + mCounter.toString()
}
}
}`
欢迎任何帮助:)
编辑:我发布了一些使用保存的首选项执行的代码,但它功能不全。我很乐意提供一些帮助 ^^
编辑 V2:查看解决方案的评论
I am really new to Android Studio(I just started yesterday) and I'm coding a sort of clicker game(in XML and kotlin).
I wanted the click counter (which is in a textview with a text at the begining) to save when leaving the app and loading when launching. I looked up savepreferences but I don't really understand how it works .. Could you guys help me please ?
`class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val one:ImageButton = findViewById<ImageButton>(R.id.iv_image)
val mp: MediaPlayer = MediaPlayer.create(this, R.raw.click)
var mCounter = 0
var txv = findViewById<TextView>(R.id.tx)
one.setOnClickListener {
//Play sound when click
mp.start()
//Increment click counter
mCounter++
txv.text = "Fixed mistakes: " + mCounter.toString()
}
}
}`
Any help is welcomed :)
EDIT: I posted some code that i did with savedpreferences but it is not fully functionnal. I would gladly appreciate some help ^^
EDIT V2: look at the comments for the solution
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编辑V2:我做到了,这是代码
`类 MainActivity : AppCompatActivity() {
}`
EDIT V2: I did it, here is the code
`class MainActivity : AppCompatActivity() {
}`