Reputation: 1040
In my application I have a settings screen that lets you change some colors of the application. I have defined the colorPrimary and colorPrimaryDark on my color resource file, and I know that after the build is complete, it is impossible to change those values.
So the way I am doing this is by saving the color Integer in the SharedPreferences:
private val preferences = context.getSharedPreferences("my.package.name", Context.MODE_PRIVATE)
var primaryColor: Int
get() = preferences.getInt("KEY_PRIMARY_COLOR", ContextCompat.getColor(context, R.color.color_primary))
set(color) {
val editor = preferences.edit()
editor.putInt("KEY_PRIMARY_COLOR", color)
editor.apply()
}
And when the user start each activity, run a method to get the settings color and change the views color:
class MainActivity : FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
setSettings()
}
private fun setSettings() {
val settings = Settings(this)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) window.statusBarColor = settings.secondaryColor
toolbar_layout.setBackgroundColor(settings.primaryColor)
add_button.backgroundTintList = ColorStateList.valueOf(settings.primaryColor)
add_button.rippleColor = settings.secondaryColor
//...
}
}
My problem here is that doing like this, I have to repeat a lot of code for all activities. Also the activities are started with the "default" color when setContentView is run, and just after that I run the setSettings and I have to re-color all the views again.
Is there any way to do this? I am concerned with repeated code and performance issues. What should be the best approach to do this?
Upvotes: 0
Views: 28
Reputation: 291
You can create a BaseActivity extend every activity from this class and place setSettings function in BaseActivity. In that way you will only write setSettings only once
Upvotes: 1