Kuffs
Kuffs

Reputation: 35661

Setting ActionMode Background programmatically

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

Is there a way to set this background in code?

Basically I need the ActionMode equavalent of

getActionBar().setBackgroundDrawable(drawable);

Upvotes: 19

Views: 2857

Answers (3)

pableiros
pableiros

Reputation: 16052

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)
}

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

Upvotes: 4

Volodymyr Machekhin
Volodymyr Machekhin

Reputation: 186

I figured out with reflection help. Because I dont have an actionbar

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) {
        }
    }

Also there are 2 implementations of ActionMode : StandaloneActionMode and ActionModeImpl. this example only for First one. For second one it will be same

Upvotes: 2

mFarouk
mFarouk

Reputation: 11

You can get the ActionMode id by using this action_context_bar

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

Upvotes: 0

Related Questions