2012-06-01 45 views
0

在我的android應用程序中,我需要動態地創建幾個LinearLayout的文本。 但我無法設定每個元素的權重。我想LL看起來像在xml部分:weightSum xml屬性代碼android

<LinearLayout 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_margin="10px" 
    android:weightSum="1" 
    android:id="@+id/qwe"> 
<TextView 
    android:layout_weight="0.1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="some" 
/> 
<TextView 
    android:layout_weight="0.8" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="word" 
/> 
<TextView 
    android:layout_weight="0.1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="here" 
    android:gravity="right" 
/> 
</LinearLayout> 

它看起來不錯,但我需要動態相同。 在Java代碼中我寫道:

LinearLayout ll = new LinearLayout(context); 
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); 
layoutParams.setMargins(10, 10, 10, 10); 
ll.setLayoutParams(layoutParams); 
ll.setOrientation(LinearLayout.HORIZONTAL); 
ll.setBackgroundColor(0xFF888888); 
rootLL.addView(ll); 

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT); 
params.setMargins(10, 10, 10, 10); 

LinearLayout.LayoutParams params1 = params; 
params1.weight = 0.15f; 
TextView one = new TextView(context); 
one.setLayoutParams(params1); 
one.setText("some"); 
ll.addView(one); 

LinearLayout.LayoutParams params2 = params; 
params2.weight = 0.7f; 
TextView two = new TextView(context); 
two.setLayoutParams(params2); 
two.setText("word"); 
ll.addView(two); 

LinearLayout.LayoutParams params3 = params; 
params3.weight = 0.15f; 
TextView three = new TextView(context); 
three.setLayoutParams(params3); 
three.setText("here"); 
ll.addView(three); 

但在這種情況下,我獲得三個TextView中的等寬。看起來我沒有爲主LL添加weightSum屬性,但我不知道該怎麼做...

請幫忙!

謝謝!

回答

4
  1. 偏好浮點數的整數。這樣你就可以得到你想要的任何一種分數(甚至1/3)。

  2. 如果您設置了每個視圖的權重,則不需要設置weightSum。

  3. 如果你設置了weightSum,你可以留下一個沒有任何重量的視圖,給它剩下的可用空間。

  4. 它看起來你給所有的意見相同的layoutparams,而不是克隆它們爲每個人。當你使用「params2 = params;」時,這意味着你設置了一個參考,而不是你創建一個新的參考。在該方法的最後,所有將指向相同的layoutParams,權重爲0.15f(因爲這是最後一個)。

+0

謝謝您的迴應!你的提示幫助了我。我錯誤的是克隆layoutparams。當我爲每個TextView創建一個新的時,一切都很好。謝謝!!! – lubart

+0

歡迎您,我建議您觀看Google IO視頻。他們可以給你很多其他的提示。對於初學者,您還可以觀看「新波士頓」視頻。 –

+0

謝謝!我會做的! :) – lubart