今天使用android:layout_weight這個屬性來實(shí)現(xiàn)一個標(biāo)題欄的布局。線上效果圖:
布局文件如下:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/id_parent" android:background="#3385ff" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="44dp"> <Button android:layout_margin="5dp" android:background="#FF0000" android:textAllCaps="false" android:id="@+id/id_btn_back" android:text="back" android:textColor="#FFFFFF" android:textSize="12sp" android:layout_gravity="center_vertical" android:gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:textAllCaps="false" android:id="@+id/id_tv_title" android:text="title" android:textSize="15sp" android:textColor="#FFFFFF" android:layout_gravity="center_vertical" android:gravity="center" android:layout_width="0dp" android:layout_weight="1" android:layout_height="wrap_content"/> <Button android:textSize="12sp" android:layout_margin="5dp" android:background="#00FF00" android:textAllCaps="false" android:id="@+id/id_btn_more" android:text="more" android:textColor="#FFFFFF" android:layout_gravity="center_vertical" android:gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content"/></LinearLayout>主要說下layout_weight的用法:android:layout_weight只能用在線性布局中android:layout_weight的真實(shí)含義是:一旦View設(shè)置了該屬性(假設(shè)有效的情況下),那么該 View的寬度等于原有寬度(android:layout_width)加上剩余空間的占比!設(shè)屏幕寬度為L,在兩個view的寬度都為match_parent的情況下,原有寬度為L,兩個的View的寬度都為L,那么剩余寬度為L-(L+L) = -L, 左邊的View占比三分之一,所以總寬度是L+(-L)*1/3 = (2/3)L.事實(shí)上默認(rèn)的View的weight這個值為0,一旦設(shè)置了這個值,那么所在view在繪制的時候執(zhí)行onMeasure兩次的原因就在這。Google官方推薦,當(dāng)使用weight屬性時,將width設(shè)為0dip即可,效果跟設(shè)成wrap_content是一樣的。這樣weight就可以理解為占比了!
新聞熱點(diǎn)
疑難解答