問題描述:這是一個簡單的網格佈局應用,計算器界面,代碼如下:
<? xml version= "1.0" encoding= "utf-8" ?>
< GridLayout xmlns: android = "http://schemas.android.com/apk/res/android"
xmlns: tools = "http://schemas.android.com/tools"
android :layout_width= "match_parent"
android :layout_height= "match_parent"
android :rowCount= "6"
android :columnCount= "4"
tools :context= "com.lifei.helloworld.TestGrid">
<!-- 定義一個橫跨 4 列的文本框,並定義前景色和背景色等屬性 -->
< TextView
android:id= "@+id/t1"
android:layout_width= "match_parent"
android:layout_height= "wrap_content"
android:textSize= "50sp"
android:padding= "3pt"
android:background= "#eee"
android:textColor= "#000"
android:text= "0" />
<Button
android:id= "@+id/clear"
android:layout_width= "match_parent"
android:layout_height= "wrap_content"
android:layout_columnSpan= "4"
android:text= " 清除 " />
<Button
android:id= "@+id/c1"
android:layout_width= "wrap_content"
android:layout_height= "wrap_content"
android:layout_column= "0"
android:layout_row= "2"
android:text= "1" />
<Button
android:id= "@+id/c2"
android:layout_width= "wrap_content"
android:layout_height= "wrap_content"
android:layout_column= "1"
android:layout_row= "2"
android:text= "2" />
<Button
android:id= "@+id/c3"
android:layout_width= "wrap_content"
android:layout_height= "wrap_content"
android:layout_column= "2"
android:layout_row= "2"
android:text= "3" />
<Button
android:id= "@+id/c4"
android:layout_width= "wrap_content"
android:layout_height= "wrap_content"
android:layout_column= "3"
android:layout_row= "2"
android:text= "4" />
</GridLayout >
圖形界面如下,可以看到,按鈕一還在,但是其餘的按鈕在外面:
原因分析:能讓按鈕1佔一行的可能原因是,該列的寬度由該列中最寬的組件決定,
而按鈕1所在的第0列,還包含上面一個TextView和一個“清除按鈕”,
所以,
①在TextView中補一句:android:layout_columnSpan= "4",那麼第0列
TextView變成了佔4列的TextView了
②如果你連“1”號按鈕也佔一行,請把相應屬性改爲:
android:layout_width= "wrap_content"