[Andriod] 以TableLayout實現Table

  • 6279
  • 0
  • 2013-04-15

...

STP1. 編輯\res\layout\activity_main.xml如下, TableLayout改名為tl


<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/horizontalScrollView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <TableLayout
        android:id="@+id/tl"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </TableLayout>
</HorizontalScrollView>


STP2. 編輯\src\com\example\table\MainActivity.java如下, 預先將資訊存於二維陣列, 再透過建立TableRow及TextView呈現資料


package com.example.table;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.ViewGroup;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class MainActivity extends Activity {
	
	private final int FP = ViewGroup.LayoutParams.FILL_PARENT;
	private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT;
	
	private String[][] SN = {
			{"SN", "WO", "PN", "LINE", "STATUS"},
			{"SN00000000000000000001", "WO00000001", "PN00000001", "A", "45"},
			{"SN00000000000000000002", "WO00000001", "PN00000001", "A", "97"},
			{"SN00000000000000000003", "WO00000001", "PN00000001", "A", "30"},
			{"SN00000000000000000004", "WO00000001", "PN00000001", "A", "30"},
			{"SN00000000000000000005", "WO00000001", "PN00000001", "A", "97"},
			{"SN00000000000000000006", "WO00000001", "PN00000001", "A", "99"},
			{"SN00000000000000000007", "WO00000001", "PN00000001", "A", "97"},
			{"SN00000000000000000008", "WO00000001", "PN00000001", "A", "9H"},
			{"SN00000000000000000009", "WO00000001", "PN00000001", "A", "01"},
			{"SN00000000000000000010", "WO00000001", "PN00000001", "A", "01"},
			{"SN00000000000000000011", "WO00000001", "PN00000001", "A", "97"},
			{"SN00000000000000000012", "WO00000001", "PN00000001", "A", "9H"}};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		this.setTitle("Table");  
        
        TableLayout tl = (TableLayout)findViewById(R.id.tl);  
        for(int r=0; r<SN.length; r++)
        {
            TableRow tableRow=new TableRow(this);
            for(int c=0; c<SN[r].length; c++)
            {
            	TextView tv=new TextView(this);
                tv.setText(SN[r][c]+"  ");
                tableRow.addView(tv);
            }
            tl.addView(tableRow, new TableLayout.LayoutParams(FP, WC));
        }
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

 

STP3. 結果如下, 拖曳滑鼠可看表格右邊的資訊