Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 入門:用程式碼動態生成 TableLayout 表格(下)

編輯:關於 Android 程式設計

上一篇初步介紹了 TableLayout 的常用屬性,這次往前一步:如何用程式碼動態地往 TableLayout 裡塞資料。這在實務中很常見——資料是執行時才拿到的,沒辦法事先寫在 XML 裡。順帶一提,九宮格也可以用同樣的思路做出來。

main.xml,用到 TableLayout 的 id 為 TableLayout01:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://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 程式碼:

 package com.LayoutDemo; import android.app.Activity; import android.os.Bundle; import android.view.ViewGroup; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; public class LayoutDemo extends Activity { 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); //新建TableLayout01的實例 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)); } } } 

執行結果:

做法就是雙層迴圈:外層負責產生 TableRow(每一行),內層往該列裡塞 TextView(每一格),最後整列加進 TableLayout。這裡呼叫的 setStretchAllColumns(true) 相當於在 XML 裡設定 android:stretchColumns="*",讓所有欄平均撐滿可用寬度——少了它,8 欄會全部擠在左側。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved