【发布时间】:2021-03-04 20:45:03
【问题描述】:
我正在创建一个歌本应用程序,我希望能够放大和缩小歌曲的歌词。我添加了缩放功能,但我希望应用程序能够记住用户离开应用程序之前歌词的文本大小。我尝试使用共享首选项,但它不起作用。
这是我目前尝试过的
class Cantare : AppCompatActivity() {
lateinit var tvSizePrefs: SharedPreferences
lateinit var tvSizeEditor: SharedPreferences.Editor
var mTextSize: Float = 50f
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.cantare)
tvSizePrefs = getSharedPreferences("TextSizePref", Context.MODE_PRIVATE)
tvSizeEditor = tvSizePrefs.edit()
setSupportActionBar(findViewById(R.id.toolbar2))
supportActionBar?.setDisplayShowTitleEnabled(false)
val songTitle = findViewById<TextView>(R.id.songTitle)
val songString = findViewById<TextView>(R.id.songString)
songString.textSize = tvSizePrefs.getFloat("TextSize", 50f)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_song, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id: Int = item.itemId
when(id) {
R.id.zoomOut -> {
mTextSize -= 2f
songString.setTextSize(TypedValue.COMPLEX_UNIT_PX, (mTextSize))
tvSizeEditor.putFloat("TextSize", mTextSize)
tvSizeEditor.apply()
Toast.makeText(this, songString.textSize.toString(), Toast.LENGTH_SHORT).show()
}
R.id.zoomIn -> {
mTextSize += 2f
songString.setTextSize(TypedValue.COMPLEX_UNIT_PX, (mTextSize))
tvSizeEditor.putFloat("TextSize", mTextSize)
tvSizeEditor.apply()
Toast.makeText(this, songString.textSize.toString(), Toast.LENGTH_SHORT).show()
}
}
return super.onOptionsItemSelected(item)
}
}
【问题讨论】:
-
您的代码是在运行还是无法编译?因为您提供的示例没有显示您在
onOptionsItemSelected中定义songString? -
嗨!它确实可以编译,只是我没有提供完整的代码。你想要完整的代码吗?
-
看起来你已经接受了一个答案,所以我想你不需要更多的帮助了吗?
-
是的,我解决了这个问题。仍然感谢您的时间。
标签: android kotlin textview sharedpreferences