如何在显示之前获得布局大小?

时间:2013-11-29 11:00:46

标签: android view

我为包含ImageViewRelativeLayout的布局进行了充气。布局的宽度设置为match_parent,高度设置为wrap_content。高度由ImageView确定,但设置为ImageView的图像是从互联网动态加载的。

由于我知道图像比例,因此我想在显示之前设置ImageView的大小,以避免因设置图像时布局高度发生变化而导致UI跳转。 / p>

要设置尺寸我需要布局宽度,以计算ImageView高度。

我试过

int width = header.getMeasuredWidth();

但由于未绘制布局,因此返回0

我之前尝试使用measure,如建议here

header.measure(0, 0);
int width = header.getMeasuredWidth();

measure会返回NullPointerException

我该怎么做?

list_header.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/pic"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <RelativeLayout
        android:id="@+id/header_text_container"
        android:layout_width="50dp"
        android:layout_height="50dp" 
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:background="#789987">
    </RelativeLayout>

</RelativeLayout>

MyListFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    mListView = (ListView) getView().findViewById(R.id.listview);

    View header = getActivity().getLayoutInflater().inflate(R.layout.list_header, null);

    int width = header.getMeasuredWidth(); // 0 because not drawn yet

    ImageView pic = (ImageView) header.findViewById(R.id.pic);
    pic.setLayoutParams(new LayoutParams(width, (int) (width/imgRatio)));

    pic.invalidate();
    header.invalidate();

    /* ... */
}

3 个答案:

答案 0 :(得分:0)

你可以在Activity的 onWindowFocusChanged(boolean hasFocus)方法中获得大小。

答案 1 :(得分:0)

您可以尝试使用ViewTreeObserver。 你的片段/活动应该在OnActivityCreate声明处理程序中实现OnGlobalLayoutListener

ViewGroup container = (ViewGroup) findViewById(R.id.header_text_container)
ViewTreeObserver vto = container.getViewTreeObserver(); 
vto.addOnGlobalLayoutListener(this);

并在大小可用时将宽度逻辑放在侦听器中

@Override
public void onGlobalLayout() {
            // Remember to remove handler
    container.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            View header = getActivity().getLayoutInflater().inflate(R.layout.list_header, null);

            int width = header.getMeasuredWidth(); // 0 because not drawn yet
            ...
}

答案 2 :(得分:0)

您可以在onGlobalLayout中获取视图的宽度和高度,这是一种方法,当视图树中的全局布局状态或视图的可见性发生变化时,将调用Callback方法(因此,一旦绘制视图并且尺寸已知)。

ViewTreeObserver vto = header.getViewTreeObserver();

if(vto!=null){
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            header.getWidth();
            header.getHeight();
        }
    });
}