如何获得 ActionBar "customView" 宽度

How to get ActionBar "customView" width

如何获得 toolbar/actionbar 的 customView 宽度,如下 highlighted

我想得到整个屏幕宽度并减去“自定义区域”的 x 坐标,但我不能t/don不知道如何得到它的 x 坐标。

val displayMetrics = DisplayMetrics()
activity.windowManager.defaultDisplay.getMetrics(displayMetrics)
val screenWidth = displayMetrics.widthPixels

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

val location = IntArray(2)
mainActivity.supportActionBar?.customView?.getLocationOnScreen(location)
val x = location[0]
val customViewWidth = screenWidth - x

你好,我有这个解决方案来获取 x 的值,它对我来说工作正常我的想法是从 action Bar 获取工具栏,从 toolBar 获取 textView:

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() {
        @Override
        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
                             */
                        }
                    }
                }
            }
        }
    });
}

希望对你有所帮助