上一篇文章,主要将如何UI设计器设计TableLayout + TableRow,由于实际应用中,经常需要在代码里往TableLayout添加数据(9宫图也可以用TableLayout做出来),本文就是介绍这方面的简单使用方法。
main.xml的代码如下,用到TableLayout的ID为TableLayout01:
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns: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>
JAVA代码如下:
- packagecom.LayoutDemo;
- importcom.LayoutDemo.R;
- importandroid.app.Activity;
- importandroid.os.Bundle;
- importandroid.view.ViewGroup;
- importandroid.widget.TableLayout;
- importandroid.widget.TableRow;
- importandroid.widget.TextView;
- publicclassLayoutDemoextendsActivity{
- /**Calledwhentheactivityisfirstcreated.*/
- privatefinalintWC=ViewGroup.LayoutParams.WRAP_CONTENT;
- privatefinalintFP=ViewGroup.LayoutParams.FILL_PARENT;
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //新建TableLayout01的实例
- TableLayouttableLayout=(TableLayout)findViewById(R.id.TableLayout01);
- //全部列自动填充空白处
- tableLayout.setStretchAllColumns(true);
- //生成10行,8列的表格
- for(introw=0;row<10;row++)
- {
- TableRowtableRow=newTableRow(this);
- for(intcol=0;col<8;col++)
- {
- //tv用于显示
- TextViewtv=newTextView(this);
- tv.setText("("+col+","+row+")");
- tableRow.addView(tv);
- }
- //新建的TableRow添加到TableLayout
- tableLayout.addView(tableRow,newTableLayout.LayoutParams(FP,WC));
- }
- }
- }
结果如下图: