Skip to content

How to get ActionBar “customView” width

How can I get the width of the customView of the toolbar/actionbar as highlighted below?

enter image description here

I had the idea to get the whole screenWidth and substract the x coordinate of the “custom area” but I can’t/don’t know how get the x coordinate of that.

val displayMetrics = DisplayMetrics()
val screenWidth = displayMetrics.widthPixels

val toolbar= mainActivity.findViewById<androidx.appcompat.widget.Toolbar>(

val location = IntArray(2)
val x = location[0]
val customViewWidth = screenWidth - x


hi i have this solution to get the value of x it’s work fine for me the idea is getting the toolbar from action Bar and the textView from toolBar:

private void getX() {
    // to get ViewContainer from ActionBar
    int id = getWindow().getDecorView().getResources().getIdentifier("action_bar_container", "id", getPackageName());
    ViewGroup v = findViewById(id);
    Log.d(TAG, "onCreate() returned: " + v.getChildCount());
    int childCount = v.getChildCount();
    //  The view tree observer can be used to get notifications when global events, like layout, happen.
    v.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        public void onGlobalLayout() {
            for (int i = 0; i < childCount; i++) {
                if (v.getChildAt(i) instanceof Toolbar) {
                    Toolbar toolbar = (Toolbar) v.getChildAt(i);
                    int toolBarChild = toolbar.getChildCount();
                    for (int j = 0; j < toolBarChild; j++) {
                        Log.e(TAG, "onCreate: " + toolbar.getChildAt(j));
                        if (toolbar.getChildAt(i) instanceof TextView) {
                            TextView tx = (TextView) toolbar.getChildAt(i);
                            int x = tx.getLeft();
                            Log.e(TAG, "onCreate: " + x); // this to get the Value of ox ( left of title )
                            Log.e(TAG, "onCreate: " + tx.getText()); // this return title in action bar
                            your code

hope that’s help you