简体   繁体   English

ImageButton 颜色在重新加载活动/应用程序时更改为默认颜色

[英]ImageButton color getting changed to default on reloading the activity/app

On button (ImageButton) click I'm changing its background color to something else but as soon as I reload the app or open another activity and come back, the button's color gets changed to default.在按钮 (ImageButton) 上单击 我正在将其背景颜色更改为其他颜色,但是一旦我重新加载应用程序或打开另一个活动并返回,按钮的颜色就会更改为默认颜色。 How can I change it permanently on click?如何在点击时永久更改它?

Thank you.谢谢你。

Currently when you change the color, it is in the scope of the activity.当前更改颜色时,它在活动的 scope 中。 What you need to do is to save the color you want to set in SharedPreferences on click on of a button.您需要做的是在单击按钮时将要设置的颜色保存在SharedPreferences中。 And when in activity's onCreate() method, set the color which is saved in the SharedPreferences to the ImageButton .在活动的onCreate()方法中,将保存在SharedPreferences中的颜色设置为ImageButton

Save the color保存颜色

private fun saveColor(color: Int) { // You will save the color ID here.
    val sharedPrefs: SharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
    sharedPrefs.edit()
        .putInt("ImageButtonColor", color)
        .apply()
}

Get The saved color获取保存的颜色

private fun getColor(): Int {
    val sharedPrefs: SharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
    return sharedPrefs.getInt("ImageButtonColor", -1)
}

In your activity's onCreate()在您的活动的onCreate()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)


    if (getColor() != -1) { // If the color is not found, function will return -1. In that case, don't change the color. It will be case for fresh installed app.
        imageButton.setBackgroundColor(ContextCompat.getColor(this, getColor())) // Get color using color ID and set to the background.
    }

    button.setOnClickListener {
        saveColor(R.color.YOUR_COLOR)
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM