【问题标题】:Remember TextView size after changing it with Shared Preferences使用共享首选项更改后记住 TextView 的大小
【发布时间】: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


【解决方案1】:

我发现您的代码有两个问题。
第一个是mTextSize 始终使用50f 进行初始化,并且您没有从保存的文本大小值中设置其值。仅在onCreate 中设置文本视图的大小。所以mTextSize总是从50f开始,当你第一次放大/缩小时,文本的大小会重置回~50f
第二个是在onCreate 中设置文本视图的大小时,您没有传递复杂的单位。
我认为将您的代码更改为这样可以解决您的问题:

override fun onCreate(savedInstanceState: Bundle?) {
    // ...
    // replace songString.textSize = tvSizePrefs.getFloat("TextSize", 50f) with:
    mTextSize = tvSizePrefs.getFloat("TextSize", 50f)
    text.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize)
    // ...
}

【讨论】:

    猜你喜欢
    • 2015-12-29
    • 2017-11-15
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多