【问题标题】:How to change the weight size of a fragment in android?如何在android中更改片段的权重大小?
【发布时间】:2012-03-28 15:47:38
【问题描述】:

这是我的片段视图的 xml 布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:weightSum="100"
     >

    <fragment
        android:id="@+id/menuFragment"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_weight="70"

        class="com.pack.Menufragment" >
    </fragment>

    <fragment
        android:id="@+id/bodyFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="30"
        class="com.pack.BodyFragment" >
    </fragment>

</LinearLayout>

现在我想从 java 而不是从 XML 更改片段权重大小,有没有办法做到这一点?

【问题讨论】:

    标签: java android


    【解决方案1】:

    我应该将 Fragments 放在单独的 LinearLayout 中并更改其权重。

    喜欢:

    <LinearLayout 
        android:id="@+id/layout1"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:layout_weight="70"
    
        <fragment
            android:id="@+id/menuFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
    
            class="com.pack.Menufragment" >
        </fragment>
    </LinearLayout>
    <LinearLayout 
        android:id="@+id/layout2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="30"
        <fragment
            android:id="@+id/bodyFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            class="com.pack.BodyFragment" >
        </fragment>
    </LinearLayout>
    

    在 Java 中

    LinearLayout layout1 = (LinearLayout) findViewById(R.id.layout1);
    android.widget.LinearLayout.LayoutParams par = layout1.getLayoutParam();
    par.weight = NEW value;
    

    【讨论】:

    • 我这样做了,但它没有显示任何错误但也没有在尺寸上生效
    【解决方案2】:

    请参考this related question。 如果您将每个片段包含在 FrameLayouts 中,然后为每个框架布局设置权重,则可以使用它。

    【讨论】:

      【解决方案3】:

      您可能想看看它是如何在这个线程中为 RelativeLayout 完成的: Android - How do I specify weight programmatically for a RelativeLayout? 应该与我假设的片段的布局参数相似,还没有尝试过,所以我不向你保证这是否会起作用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-22
        • 2012-12-05
        • 1970-01-01
        • 2023-03-22
        • 2016-09-17
        • 2011-04-11
        • 2021-09-30
        • 2019-12-05
        相关资源
        最近更新 更多