onGlobalLayout()可能在视图布局之前被调用。

3
我的Firebase崩溃报告显示以下代码在极少数设备上出现故障。我无法重现此问题。是否有人能提出可能的问题?似乎问题是imageView.getWidth()或imageView.getHeight()返回零。
以下代码位于我的fragment中:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_category_list, container, false);

    final ImageView imageView = (ImageView) view.findViewById(R.id.categoryBackgrndImageView);

    // Set an observer that is called after the imageView is laid out
    imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            //now we can retrieve the width and height
            int width = imageView.getWidth();
            int height = imageView.getHeight();

            // etc. Code here removed. It gets an asset and creates a bitmap from the
            // asset, sizing the bitmap based on the imageView width and height
        } 

这是布局:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:menu="menu_main,menu_categories">

<ImageView
    android:id="@+id/categoryBackgrndImageView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="centerCrop" />

<technology.grandma.margriver.AutoGridRecylerView
    android:id="@+id/categoryRecyclerView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:columnWidth="330dp"
    android:scrollbars="vertical"
    tools:listitem="@layout/list_item_category"/>

</FrameLayout>

我的互联网研究似乎证实了这段代码是正确的。你能看出有什么问题吗?

1个回答

0

尝试使用OnLayoutChangeListener代替:

imageView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        int width = imageView.getMeasuredWidth();
        int height = imageView.getMeasuredHeight();
        imageView.removeOnLayoutChangeListener(this);
    }
});

OnGlobalLayoutListener 观察所有层次结构的布局更改,因此在层次结构中放置任何视图时,可能会触发它。此时也更有可能知道 measuredWidthmeasuredHeight


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接