actionBar = activity.actionBar ?: when (activity) {
is AppCompatActivity -> activity.supportActionBar
else -> null
}
//view有默认实现
private val drawableCallback = object : Drawable.Callback {
override fun invalidateDrawable(who: Drawable) {
actionBar?.run {
if (this is android.app.ActionBar) {
setBackgroundDrawable(who)
} else if (this is ActionBar) {
setBackgroundDrawable(who)
}
}
}
override fun scheduleDrawable(drawable: Drawable, action: Runnable, time: Long) {
Handler().postAtTime(action, time)
}
override fun unscheduleDrawable(drawable: Drawable, action: Runnable) {
Handler().removeCallbacks(action)
}
}
fun setActionBarColor(@ColorInt color: Int) {
actionBar?.let { ab ->
val colorDrawable = ColorDrawable(color)
oldActionBarBackground?.let { oldBackground ->
val td = TransitionDrawable(arrayOf(oldBackground, colorDrawable))
// workaround for broken ActionBarContainer drawable handling on pre-API 17 builds
// https://github.com/android/platform_frameworks_base/commit/a7cc06d82e45918c37429a59b14545c6a57db4e4
when {
Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1 -> td.callback = drawableCallback
ab is android.app.ActionBar -> ab.setBackgroundDrawable(td)
ab is ActionBar -> ab.setBackgroundDrawable(td)
}
td.startTransition(200)
} ?: run {
when {
Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1 -> {
val td = TransitionDrawable(arrayOf<Drawable>(colorDrawable, colorDrawable))
td.callback = drawableCallback
td.startTransition(200)
}
ab is android.app.ActionBar -> ab.setBackgroundDrawable(colorDrawable)
ab is ActionBar -> ab.setBackgroundDrawable(colorDrawable)
}
}
oldActionBarBackground = colorDrawable
// http://stackoverflow.com/questions/11002691/actionbar-setbackgrounddrawable-nulling-background-from-thread-handler
if (ab is android.app.ActionBar) {
val isDisplayingTitle = ab.displayOptions and android.app.ActionBar.DISPLAY_SHOW_TITLE != 0
ab.setDisplayShowTitleEnabled(!isDisplayingTitle)
ab.setDisplayShowTitleEnabled(isDisplayingTitle)
} else if (ab is ActionBar) {
val isDisplayingTitle = ab.displayOptions and ActionBar.DISPLAY_SHOW_TITLE != 0
ab.setDisplayShowTitleEnabled(!isDisplayingTitle)
ab.setDisplayShowTitleEnabled(isDisplayingTitle)
}
}
}
网友评论