Layout

主要分和靜態定義和動態程式兩部分說明。

Android裡有五個主要的排版元件

  • FrameLayout
  • LinearLayout
  • AbsoluteLayout
  • RelativeLayout
  • TableLayout

使用 LinearLayout 的時機:

  • 無序列表項目需要設計依比例排列元件時。
  • 需要設計符合多種尺寸的裝置時。

LinearLayout 的 XML 屬性:

ViewNameTypeDescription
LinearLayoutbaselineAlignedboolean當設定為 false,可以避免 Layout 去調整子元素的基線
:::baselineAlignedChildIndexR.id指定對齊子元素的基線
:::dividerDrawable設定分格線
:::gravityR.attr.layout_gravity設定子元件的對齊方法
:::measureWithLargestChildboolean如果是 true 的話,所有子元素的 weight 都會被視為最大尺寸的最小尺寸
:::orientationR.attr.orientation設定方向,horizontal 為橫向,vertical 為直向
:::weightSumint定義 weight 的總合

LinearLayout 子元素可以用的 XML 屬性:

layout_weight 設定的重點:

  • 在 layout_width 設置為 fill_parent 的時候,layout_weight 所代表的是你的控件要優先盡可能的大,但這個大是有限度的,即 fill_parent。
  • 在 layout_width 設置為 wrap_content 的時候,layout_weight 所代表的是你的控件要優先盡可能的小,但這個小是有限度的,即 wrap_content。

使用 RelativeLayout 的時機:

  • 當子元素必需重疊覆蓋時

使用 TableLayout 的時機很明確,當需要做表格排版時就是用 TableLayout 了。

TextView 不會自動換行,可以在 TableLayout 加入下面的屬性即可:

  • android:shrinkColumns="0,3,4" 表示0 3 4欄可以伸縮。
  • android:shrinkColumns="*" 表示所有行可以伸缩。

API Level 14+ needed,需使用android.support.v7 才能支援舊版本。

Gradle build script dependency identifier:

com.android.support:gridlayout-v7:18.0.+

常用屬性

ViewNameTypeDescription
GridLayoutcolumnCountint設定螢幕分割的欄數,編號從 0 開始
:::rowCountint設定螢幕分割的列數,編號從 0 開始
Children Viewlayout_columnint指定 View 要放在哪一欄
:::layout_rowint指定 View 要放在哪一列
:::layout_columnSpanint指定 View 要跨幾個欄
:::layout_rowSpanint指定 View 要跨幾個列

使用 LayoutInflater 取得 Layout 的方法 參考

方法一:

// in Activity
LayoutInflater inflater = LayoutInflater.from(this);  
View layout = inflater.inflate(R.layout.main, null);

方法二:

// in Activity
LayoutInflater inflater = getLayoutInflater();  
View layout = inflater.inflate(R.layout.main, null);  

方法三:

// in Activity
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);  
View layout = inflater.inflate(R.layout.main, null);  

上面的方法,如果第二個參數傳 null 會被 Android Lint 說有問題,可以參考這篇: