在片段的onCreateView中获取子布局(包括子元素)的高度



我在片段中使用的布局大小始终为0。

我有一个片段,其中包括一个子布局,看起来像这样:

 <RelativeLayout android:id="@+id/animationLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="30dp"
    android:background="@color/colorPrimary"
    android:elevation="4dp">

此布局有一个子布局,其定义如下:

  <TableLayout android:id="@+id/searchForm"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:stretchColumns="0"
            android:background="@color/colorPrimary"
            android:descendantFocusability="beforeDescendants"
            android:focusableInTouchMode="true">
            [Some Child elements]
</TableLayout>

在父片段的onCreateView中,布局"searchForm"的高度始终为0。

即使我在中测量尺寸

searchForm.post(new Runnable() {
     @Override
     public void run() {
        searchFormHeight = searchForm.getHeight(); //always 0
     }
}

大小为0。

如何在onCreateView中获取此布局的大小?

当整个视图膨胀时,您需要使用ViewTreeListener进行回调。如果我记得android会等待整个视图同时膨胀,所以即使一个视图被安装,它也可能不会膨胀,返回0的高度。

searchForm.getViewTreeObserver()
     .addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
     @Override
     public boolean onPreDraw () {
        searchFormHeight = searchForm.getHeight();
        return true;
});

好吧,我不知道我以前做错了什么,但最终以下对我有效:

 searchForm.post(new Runnable() {
         @Override
         public void run() {
            searchFormHeight = searchForm.getHeight();
         }
  });

实际上onCreateView()处理视图的创建,这就是它返回0 的原因

尝试以下获取高度,将函数覆盖到片段类中

@Override
public void onConfigurationChanged(Configuration newConfig) 
{
    super.onConfigurationChanged(newConfig);
    searchFormHeight = searchForm.getHeight();
}