5

我想事先知道视图的大小。我用这种方法测量它的大小。

public static int[] measureSize(ViewGroup parent, int layoutId)
{
    View view = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);
    final int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    view.measure(spec, spec);
    final int width = view.getMeasuredWidth(); // ? 0, not include compound drawable size and relative padding. WHY
    final int height = view.getMeasuredHeight();
    return new int[]{width, height};
}

这是布局文件:

<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableStart="?android:listChoiceIndicatorSingle"
    android:drawablePadding="20dp"/>

问题:测量的视图宽度并不总是包括复合可绘制尺寸及其相关填充。如果我不设置文本,则测量的宽度始终为 0。如果设置非空值,则宽度仅适用于文本。为什么?我怎样才能得到正确的尺寸?

提前致谢。

4

0 回答 0