Set Fragment height programmatically according to existing elements

Pre:

  • I am extending the relativelayout class and inflating the below reduced xml sample
  • I am adding the fragment programmatically in the container layout "fragment_container"
  • What I want to achieve is to add a fragment in a layout-container (in this case fragment_container) where the height is already ruled by the three textviews

    <merge xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    
    <TextView
        android:layout_marginTop="10dp"
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text 1" />
    
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"
        android:text="New Text 2" />
    
    <TextView
        android:layout_marginBottom="10dp"
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView2"
        android:text="New Text 3" />
    </RelativeLayout>
    

    To set the height of the fragment programmatically I am doing this:

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
    
        if (!hasFocus) return;
    
        ViewGroup.LayoutParams params = fragment.getView().getLayoutParams();
        params.height = getMeasuredHeight();
        params.width = getMeasuredWidth();
        fragment.getView().setLayoutParams(params);
    }
    

    This solution works sometimes (sometimes getMeasuredHeight returns 0 && getMeasuredWidth returns 0), so it's not the correct solution.

    Is this a problem that can be solved through the use of the xml only?


    正如我看到你垂直堆叠视图,使用LinearLayout垂直方向不是更好,并给每个视图适当的权重(0为高度,适当的重量值)?

    链接地址: http://www.djcxy.com/p/68746.html

    上一篇: 算法来比较两个图像

    下一篇: 根据现有元素以编程方式设置片段高度