關於版面 weight 權重的設計,
可以用 Layout 搭配 android:layout_weight 屬性,
或用以下程式碼設定 :
程式碼
obj.setLayoutParams( new LayoutParams( LayoutParams.WRAP_CONTENT , LayoutParams.WRAP_CONTENT , 1f // 權重值 ) );
均可以實現物件在版面中所佔的比例 (權重),
1)
優先權的判斷:
若是 水平排列, 則 layout_width = 數值 > layout_weight (需搭配 layout_width = WRAP_CONTENT)
若是 垂直排列, 則 layout_height= 數值 > layout_weight (需搭配 layout_height= WRAP_CONTENT)
2)
該屬性值預設為 0, 也就是不會自動分配.
範例, 參考如下 :
Layout 範例 :
Layout XML
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 1"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="Button 2"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 3"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button 4"
/>
</LinearLayout>
</LinearLayout>
程式範例 :
程式碼
public class TomTest extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView( R.layout.main_test );
}
}
範例結果 :
(Button1 與 Button2 的 layout_weight 比例為 1:2, 照理說, 顯示寬度比也要為 1:2)
(但實際上顯示非如此, 這點實在不清楚原因, 但可以改用程式中動態設定寬度)

