'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. How can I change it permanently on click ?

Thank you.



Solution 1:[1]

Currently when you change the color, it is in the scope of the activity. What you need to do is to save the color you want to set in SharedPreferences on click on of a button. And when in activity's onCreate() method, set the color which is saved in the SharedPreferences to the 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()

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)
    }

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vikas Choudhary