這樣的需求如果在iOS中,基本的思路是獲取當前屏幕的寬度screen_width,然后用一個CGFloat類型的變量temp_width記錄一下screen_width / 4.f的計算結果,在用temp_width為按鈕的width賦值。不管是frame布局還是autolayout布局方式,基本都這樣。
但是安卓中實現這樣的效果,用的是“布局模式 + 不給定寬度 + 權重”。感覺很優美~
代碼如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal"> <Button android:layout_width="0dip" android:layout_weight="1" android:layout_height="@dimen/dp_40" android:text="水果" /> <Button android:layout_width="0dip" android:layout_weight="1" android:layout_height="@dimen/dp_40" android:text="蔬菜類" /> <Button android:layout_width="0dip" android:layout_weight="1" android:layout_height="@dimen/dp_40" android:text="飲料" /> <Button android:layout_width="0dip" android:layout_weight="1" android:layout_height="@dimen/dp_40" android:text="燒烤一下" /> </LinearLayout>
效果圖如下:
參考:【android開發兩個按鈕各占屏幕一半擺放的方法】