以编程方式设置ActionMode背景

问题描述:

我知道可以在XML主题中使用的android:actionModeBackground.

I am aware of android:actionModeBackground that can be used in XML themes.

有没有办法在代码中设置背景?

Is there a way to set this background in code?

基本上我需要等价的ActionMode

Basically I need the ActionMode equavalent of

getActionBar().setBackgroundDrawable(drawable);

在使用Android Studio 3.4.2的Kotlin中:

In Kotlin using Android Studio 3.4.2:

(actionMode as? StandaloneActionMode).let {
    val contextView = it?.javaClass?.getDeclaredField("mContextView")
    contextView?.isAccessible = true

    val standActionMode = contextView?.get(it)
    val color = ContextCompat.getColor(context, R.color.colorResId)
    (standActionMode as? View)?.setBackgroundColor(color)
}

要将actionMode强制转换为StandaloneActionMode,请不要忘记从androidx.appcompat.view.ActionMode而不是从android.view.ActionMode导入ActionMode.

To cast actionMode to StandaloneActionMode, don't forget to import ActionMode from androidx.appcompat.view.ActionMode and not from android.view.ActionMode.