【发布时间】:2019-10-10 12:32:40
【问题描述】:
我正在使用 Kotlin 开发游戏。我的目标是,每次用户按下特定按钮时,他都会在现有硬币中添加 20 个硬币。之后,应该使用共享偏好保存硬币编号。
共享偏好:
val sharedPreferences = getSharedPreferences("SP_INFO", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
var coins = preferenceFile.getInt("COINS", 0)
这是显示硬币编号的文本视图的布局:
//Coin Label
<TextView android:id="@+id/coinlabel"
android:layout_width="150dp"
android:layout_height="60dp"
android:textSize="40sp"
android:textColor="@color/coinlabel"
android:textAlignment="textStart"
android:layout_marginTop="20dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
/>
我尝试将 20 个硬币添加到现有硬币中,但它并没有像我想要的那样工作。
var coins = Int
button.setOnClickListener {
coins = 20 + coins //The plus symbol may be used wrong here
editor.putInt("COINS",coins)
editor.apply() //Here I want to save the coins number to shared-preferences
coinlabel.setText(Integer.toString(coins))
println(coins)
}
全班:
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import kotlinx.android.synthetic.main.activity_main.*
import android.animation.ObjectAnimator
import android.animation.AnimatorSet
import android.content.Intent
import android.net.Uri
import android.view.MotionEvent
import android.content.Context
import android.media.MediaPlayer
class MainActivity : AppCompatActivity() {
val sharedPreferences = getSharedPreferences("SP_INFO", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
var coins = sharedPreferences.getInt("COINS", 0)
var pressed: Boolean? = false
var audioon = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportActionBar?.hide()
this.getWindow()
.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
soundon.setOnClickListener{
audioon = false
editor.putBoolean("AUDIOON", audioon)
editor.apply()
}
soundoff.setOnClickListener {
audioon = true
editor.putBoolean("AUDIOON", audioon)
editor.apply()
}
button.setOnClickListener {
coins += 20
coinlabel.setText(Integer.toString(coins))
editor.putInt("COINS",coins)
editor.apply()
println(coins)
}
}
}
【问题讨论】:
-
你希望它如何工作?
-
我在问题的开头说了我想要实现的目标。 @TaseerAhmad
-
您想将硬币添加到共享偏好中的现有硬币中,但您实际上正在做的是删除以前存储的硬币并添加新硬币?这是怎么回事?
-
我不想删除以前存储的硬币。我怎样才能防止这种情况发生? @TaseerAhmad
-
什么是
preferenceFile?
标签: android kotlin textview sharedpreferences