鴻蒙HarmonyOS Java UI之TableLayout布局示例
https://harmonyos.51cto.com/#zz
TableLayout簡介
TableLayout意為表格布局,也可以稱為網格布局,允許我們使用表格的方式來排列組件,也就是行和列的方式。
TableLayout提供了用于在表格中對齊和排列組件的接口。可配置表格的排列方式,行數和列數,以及組件的位置。
常用屬性
ohos:alignment_type表示設置網格布局中的對齊方式,默認為align_contents(表示頁邊距對齊),還有一個參數是align_edges(表示邊界對齊)。
- xmlns:ohos="http://schemas.huawei.com/res/ohos"
- ohos:id="$+id:tableLayout"
- ohos:height="match_parent"
- ohos:width="match_parent"
- ohos:alignment_type="align_contents"
- ohos:background_element="#8AA7AA">
ohos:row_count表示設置網格布局中行數,ohos:column_count表示設置網格布局中的列數。如果沒有為子組件設置值,則使用父組件默認的行數和列數。在網格布局中若子組件的數量超出列數設置,則會自動添加行數。比如下列代碼,我們設置一行,兩列,但是是三個子組件,我們監聽其中一個按鈕的點擊事件,將行列數顯示在文本組件中。
- xmlns:ohos="http://schemas.huawei.com/res/ohos"
- ohos:id="$+id:tableLayout"
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:row_count="1"
- ohos:column_count="2"
- ohos:background_element="#8AA7AA">
- ohos:id="$+id:tableTxt"
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:text="我是文本組件"
- ohos:text_size="20fp"/>
- ohos:id="$+id:button"
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:text="我是第一個按鈕"
- ohos:background_element="#5C6E71"
- ohos:text_color="#FFFFFF"
- ohos:text_size="20fp"/>
- ohos:id="$+id:btn"
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:text="我是第二個按鈕"
- ohos:background_element="#5C6E71"
- ohos:text_color="#FFFFFF"
- ohos:text_size="20fp"/>
未觸發按鈕點擊事件的時候頁面顯示效果。

觸發按鈕點擊事件的時候頁面顯示效果。

ohos:orientation表示設置表格中組件的排列方式,水平(vertical)和垂直(horizontal)。如果我們設置行為1,列為2,子組件三個,設置水平方向顯示,那么我們的列將失效,自動會添加一列。
- xmlns:ohos="http://schemas.huawei.com/res/ohos"
- ohos:id="$+id:tableLayout"
- ohos:height="match_parent"
- ohos:width="match_parent"
- ohos:orientation="horizontal"
- ohos:background_element="#8AA7AA">
- xmlns:ohos="http://schemas.huawei.com/res/ohos"
- ohos:id="$+id:tableLayout"
- ohos:height="match_parent"
- ohos:width="match_parent"
- ohos:orientation="vertical"
- ohos:background_element="#8AA7AA">
示例
- xmlns:ohos="http://schemas.huawei.com/res/ohos"
- ohos:id="$+id:tableLayout"
- ohos:height="match_parent"
- ohos:width="match_parent"
- ohos:row_count="3"
- ohos:column_count="5"
- ohos:background_element="#8AA7AA">
- ohos:height="match_content"
- ohos:width="match_content"
- ohos:text="我是第1個按鈕"
- ohos:background_element="#07CCFF"
- ohos:text_color="#FFFFFF"
- ohos:text_size="20fp"
- ohos:padding="10vp"/>
- .....
https://harmonyos.51cto.com/#zz