tablelayout布局說白了就和jsp頁面的table布局是一樣的,一個table包含幾行幾列。
下面有一段代碼,
public class LayoutDemo extends Activity {
// wc和fp兩個屬性,是布局用的,wc表示wrap_content剛好包含內容,FP則是填充滿父容器
private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT;
private final int FP = ViewGroup.LayoutParams.FILL_PARENT;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//根據id屬性,擷取tablelayout對象
TableLayout tableLayout = (TableLayout)findViewById(R.id.TableLayout01);
//自動填滿空白(表示當前行如果有空餘的空間,則自動展開內容填充滿該行)
tableLayout.setStretchAllColumns(true);
//產生10行,8列的表格
for(int row=0;row<10;row++)
{
TableRow tableRow=new TableRow(this); //建立一行
for(int col=0;col<8;col++)
{
//tv用於顯示
TextView tv=new TextView(this); // 建立一個儲存格
tv.setText("("+col+","+row+")");
tableRow.addView(tv);
}
//建立的TableRow添加到TableLayout
tableLayout.addView(tableRow, new TableLayout.LayoutParams(FP, WC));
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TableLayout
android:id="@+id/TableLayout01"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TableLayout>
</LinearLayout>
代碼很短,但是很不助於學習。跟我一樣的初學者要受苦了。實際上,說白了,道理是這樣的:
一個tableLayout,相當於一個表格。
一個tableRow ,相當於一行。
一個textView相當於一個儲存格。
這樣層級關係就清楚了,
1/儲存格textView要放在行tableRow裡面。
tableRow.addView(textView);
2/一行要放在表格裡
tableLayout.addView(tableRow);
: