我有一個垂直的LinearLayout LL_p和兩個子水平的LinearLayouts LL_1和LL_2,它們又有它們自己的子項。基於LL_1和LL_2的可見內容,我想動態地改變它們在LL_p中的相對權重。我已經有了一個xml佈局,其中有很多細節我不想丟失,所以我只需要對權重進行增量更改。我怎麼做?下面是我的XML編程設置LinearLayout的子項的權重
…
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=「0.2」
android:orientation="vertical" >
<LinearLayout
android:id="@+id/ll_1」
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.55"
android:background="@drawable/some_image」
android:orientation="vertical" >
<!—- a number of includes —>
</LinearLayout>
<LinearLayout
android:id="@+id/ll_2」
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.45"
android:layout_marginBottom="@dimen/dim_1」
android:background="@color/some_color」
android:orientation="horizontal" >
<!—- a number of children —>
</LinearLayout>
</LinearLayout>
</LinearLayout>
所以在Java活動課我想我需要下面的方法,但我需要幫助完成它。請注意,我沒有實例化新的佈局參數,因爲這會導致我失去我的xml佈局細節;相反,我使用getLayoutParams
從xml中獲取一組。那麼我如何才能使體重改變到所獲得的佈局呢?
private void adjustMYLayout(boolean flip) {
LayoutParams layout1 = mLL1.getLayoutParams();
LayoutParams layout2 = mBLL2.getLayoutParams();
//now what?
if(flip) {//set one weight system
}else {
//set other weight system
}
}
更新@nKn
private void adjustMYLayout(boolean flip) {
if (flip) {
mLL1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.8f));
mLL2.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.2f));
} else {
mLL1.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.55f));
mLL2.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT, 0.45f));
}
}
可能重複的[Android的線性佈局權重編程](http://stackoverflow.com/questions/19158327/android-linear-layout-weight-programatically) – starkej2