现在的位置: 首页 > 综合 > 正文

android之tableLayout布局之一

2013年08月20日 ⁄ 综合 ⁄ 共 1717字 ⁄ 字号 评论关闭

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);

效果图:

 

抱歉!评论已关闭.