如何在膨胀视图中强制调用 OnGlobalLayoutListener

How to force call to OnGlobalLayoutListener in inflated view

我正在使用调用

膨胀视图
final View view = mActivity.getLayoutInflater().inflate(R.layout.photo_view, null, false);

放大视图的唯一目的是将其转换为位图。

以下呼叫无效。现在,如果我在 DialogFragment 的 onCreateView 中进行调用,它就可以工作——所以我知道代码片段本身可以工作。但是,如果我只是为位图转换膨胀视图,则永远不会调用方法 public void onGlobalLayout()

ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
    if (viewTreeObserver.isAlive()) {
        Log.i(TAG, "waiting for right time");
        view.getViewTreeObserver().addOnGlobalLayoutListener(new
            ViewTreeObserver.OnGlobalLayoutListener() {
                @SuppressLint("NewApi")
                @Override
                public void onGlobalLayout() {

                    if (view.getLayoutParams().width <= 0 || view.getLayoutParams().height <= 0) {
                        int height = getDeviceHeight(mActivity);
                        int width = getDeviceWidth(mActivity);
                        LayoutParams layout = view.getLayoutParams();
                        layout.height = height;
                        layout.width = width;
                        view.setLayoutParams(layout);
                    }

                    doMyWork(view);
                    if (Utils.hasJellyBean()) {
                        view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    } else {
                        view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    }

                }
            });
    }

我需要这个方法,因为我想要一个非零维度来创建我的位图,否则我会得到 null,比如 view.getDrawingCache()。那么如何强制执行 ViewTreeObserver.OnGlobalLayoutListener

您的视图永远不会附加到 window -- 它永远不会由框架布置。您需要将它附加到 window(例如,将它放在您的布局中的某个地方)或手动测量和布局。

int widthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
int heightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);

view.measure(widthSpec, heightSpec);
view.layout(view.getMeasuredWidth(), view.getMeasuredHeight());

您的视图未附加到 window。添加 onGlobalLayoutListener 后尝试调用 view.requestLayout()