Setting ActionMode Background programmatically

蓝咒 提交于 2020-01-31 06:23:37

问题


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

回答1:


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




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/17089189/setting-actionmode-background-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!