Stack Overflow archive
3 score

How to get ActionBar view?

score
3
question views
29.9K
license
CC BY-SA 3.0

This will get the Toolbar/ActionBar when using the native ActionBar, your own Toolbar from appcompat, or the native Toolbar on Lollipop:

java
public static ViewGroup findActionBar(Activity activity) {
    int id = activity.getResources().getIdentifier("action_bar", "id", "android");
    ViewGroup actionBar = null;
    if (id != 0) {
        actionBar = (ViewGroup) activity.findViewById(id);
    }
    if (actionBar == null) {
        actionBar = findToolbar((ViewGroup) activity.findViewById(android.R.id.content)
                .getRootView());
    }
    return actionBar;
}

private static ViewGroup findToolbar(ViewGroup viewGroup) {
    ViewGroup toolbar = null;
    for (int i = 0, len = viewGroup.getChildCount(); i < len; i++) {
        View view = viewGroup.getChildAt(i);
        if (view.getClass().getName().equals("android.support.v7.widget.Toolbar")
                || view.getClass().getName().equals("android.widget.Toolbar")) {
            toolbar = (ViewGroup) view;
        } else if (view instanceof ViewGroup) {
            toolbar = findToolbar((ViewGroup) view);
        }
        if (toolbar != null) {
            break;
        }
    }
    return toolbar;
}

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.