首页 > 解决方案 > 如何获得 ActionBar “customView” 宽度

问题描述

如何获得如下突出显示的工具栏/操作栏的宽度customView

在此处输入图像描述

我的想法是获得整个 screenWidth 并减去“自定义区域”的 x 坐标,但我不能/不知道如何获得它的 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

标签: javaandroidkotlintoolbarandroid-toolbar

解决方案


嗨,我有这个解决方案来获取 x 的值,它对我来说很好,这个想法是从操作栏获取工具栏,从工具栏获取 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
                             */
                        }
                    }
                }
            }
        }
    });
}

希望对你有帮助


推荐阅读