以编程方式设置ActionMode Background

时间:2013-06-13 14:07:28

标签: android android-actionbar

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

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

基本上我需要等于

的ActionMode
getActionBar().setBackgroundDrawable(drawable);

3 个答案:

答案 0 :(得分:0)

您可以使用此action_context_bar

获取ActionMode ID
   int amId = getResources().getIdentifier("action_context_bar", "id", "android");
   View view= findViewById(amId);
   view.setBackground(actionModeBackground);

答案 1 :(得分:0)

我想出了反思帮助。因为我没有动作栏

public static void setActionModeBackgroundColor(ActionMode actionMode, int color) {
        try {
            StandaloneActionMode standaloneActionMode = (StandaloneActionMode) actionMode;
            Field mContextView = StandaloneActionMode.class.getDeclaredField("mContextView");
            mContextView.setAccessible(true);
            Object value = mContextView.get(standaloneActionMode);
            ((View) value).setBackground(new ColorDrawable(color));
        } catch (Throwable ignore) {
        }
    }

还有2个ActionMode实现:StandaloneActionMode和ActionModeImpl。这个例子仅适用于第一个。对于第二个,它将是相同的

答案 2 :(得分:0)

在Kotlin中使用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,请不要忘记从ActionMode而不是从androidx.appcompat.view.ActionMode导入android.view.ActionMode

相关问题