2013年12月26日 星期四

2013/12/26【程式日記】靜音課表-動態新增元件(格線)

    如何設定表格這個問題讓我想了非常久..,如果是一開始就設定死死的話 那後面就完全沒有變化性了,維修也會很困難,於是開始尋找了動態新增元件的方法,首先是在手機 activity_main.xml 的地方設定一個TableLayout ,並在程式內設定顏色,卻發現設定好顯示出來時並沒有格線。
    格線讓我頭疼了很久,網路上的教學都是直接在activity_main裡面寫好好android:layout_margin去設定,可是當動態新增元件時,範例並不是特別多,要注意的地方也比較少,這個是最後研究出的方式


// 建立表格
private void setTable() {
tl.setBackgroundColor(Color.parseColor("#111111"));
tr = new TableRow[classcount];
classtime = new TextView[classcount];
classcontent = new TextView[weekcount][classcount];
TableLayout.LayoutParams tableRowParams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT);
tableRowParams.setMargins(0, 1, 0, 1);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.setMargins(1, 1, 1, 1);
for (int i = 0; i < classcount; i++) {
tr[i] = new TableRow(getApplication());
tr[i].setBackgroundColor(Color.parseColor("#555555"));
tr[i].setLayoutParams(tableRowParams);
classtime[i] = new TextView(getApplication());
classtime[i].setBackgroundColor(Color.parseColor("#ffffff"));
classtime[i].setText("test." + i);
tr[i].addView(classtime[i], params);
for (int j = 0; j < weekcount; j++) {
classcontent[j][i] = new TextView(getApplication());
classcontent[j][i].setText("test." + (j + 1) + "." + i);
classcontent[j][i].setBackgroundColor(Color
.parseColor("#ffffff"));

tr[i].addView(classcontent[j][i], params);
}
tl.addView(tr[i]);
}
}