下面的代码有效,但我觉得可能会有更高效/更清晰的方式。我是Kotlin和Android开发人员的新手,所以请对我轻松点。 ;-)任何增强将非常赞赏,因为我一直在寻求改进。试图编写高效的代码来使用Kotlin更新背景颜色
fun updateBackgroundColor() {
val sharedPref = PreferenceManager.getDefaultSharedPreferences(this)
// Gets the text color from the shared preferences file
val backgroundColor = sharedPref.getString("background_color", "")
val fullscreenView = findViewById(R.id.fullscreen_content)
val fullView = fullscreenView as TextView?
// Changes the text color based on the color the user has selected in Settings/Preferences
if (backgroundColor == "blue") {
fullView!!.setBackgroundColor(ContextCompat.getColor(this, mBlue))
} else if (backgroundColor == "red") {
fullView!!.setBackgroundColor(ContextCompat.getColor(this, mRed))
} else if (backgroundColor == "green") {
fullView!!.setBackgroundColor(ContextCompat.getColor(this, mGreen))
} else if (backgroundColor == "yellow") {
fullView!!.setBackgroundColor(ContextCompat.getColor(this, mYellow))
} else if (backgroundColor == "purple") {
fullView!!.setBackgroundColor(ContextCompat.getColor(this, mPurple))
} else if (backgroundColor == "pink") {
fullView!!.setBackgroundColor(ContextCompat.getColor(this, mPink))
} else if (backgroundColor == "black") {
fullView!!.setBackgroundColor(ContextCompat.getColor(this, mBlack))
} else if (backgroundColor == "white") {
fullView!!.setBackgroundColor(ContextCompat.getColor(this, mWhite))
} else {
fullView!!.setBackgroundColor(ContextCompat.getColor(this, mBlue))
}
}
是你正在寻找一个代码审查这方面的工作代码?如果是这样,它可能更适合我们的[CodeReview.se]网站。 – EJoshuaS
感谢您的注意。我不知道那是存在的。我会在那里发帖。谢谢! – Dallas
我的第一个想法,顺便说一句,这似乎像Kotlin的'switch'语句的等价物在这里可能更容易阅读。 – EJoshuaS