下記に試行錯誤した例を記載します。
①text.setWidth()を利用。
→コンパイルエラーや、実行時エラーにはならないが、setWidth()が無視されてしまう。
TableLayout tableLayout = new TableLayout(this);
setContentView(tableLayout, new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
TableRow tableRow;
tableRow = new TableRow(this);
TextView text = new TextView(this);
text.setTextSize(12); //表示テキストサイズ
text.setWidth(40); //横幅
text.setGravity(Gravity.CENTER); //表示位置(中央)
tableRow.addView(text); //TableLayoutの行にTextViewを追加
tableLayout.addView(tableRow); //TableLayoutに行を追加
②TableLayout.LayoutParamsを利用。
→実行時にアプリケーションが異常終了した。(コンパイルエラー無)
TableLayout tableLayout = new TableLayout(this);
setContentView(tableLayout, new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
TableRow tableRow;
tableRow = new TableRow(this);
TextView text = new TextView(this);
LayoutParams lp = new LayoutParams(40, LayoutParams.FILL_PARENT);
text.setTextSize(12); //表示テキストサイズ
text.setWidth(40); //横幅
text.setGravity(Gravity.CENTER); //表示位置(中央)
tableRow.addView(text,lp); //TextViewをサイズ指定で追加
tableLayout.addView(tableRow); //TableLayoutに行を追加
③TableRow.LayoutParamsを利用。
→解決(指定したサイズで表示された)
TableLayout tableLayout = new TableLayout(this); setContentView(tableLayout, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); TableRow tableRow; tableRow = new TableRow(this); TextView text = new TextView(this); TableRow.LayoutParams text_layout_params = new TableRow.LayoutParams(40,40); text.setLayoutParams(text_layout_params); //TableRow.LayoutParamsを利用 text.setTextSize(12); //表示テキストサイズ text.setWidth(40); //横幅 text.setGravity(Gravity.CENTER); //表示位置(中央) tableRow.addView(text,lp); //TextViewをサイズ指定で追加 tableLayout.addView(tableRow); //TableLayoutに行を追加