27

プログラムで TableLayout を作成しようとしています。それはうまくいきません。ただし、xml ファイルの同じレイアウトが機能します。これは私が持っているものです:

public class MyTable extends TableLayout
{
    public MyTable(Context context) {
        super(context);

        setLayoutParams(new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        TableRow row = new TableRow(context);
        row.setLayoutParams(new TableRow.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

        Button b = new Button(getContext());
        b.setText("hello");
        b.setLayoutParams(new LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
        row.addView(b); 
        addView(row)
    }
}

...

// In main activity:
MyTable table = new MyTable(this);
mainLayout.addView(table);

これを実行すると、クラッシュはしませんが、何も表示されません。TableRow インスタンスを削除すると、少なくともボタンは TableLayout の直接の子として表示されます。私は何を間違っていますか?

4

5 に答える 5

39

答えをより明確にするために:

TableLayout.LayoutParams tableParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
TableRow.LayoutParams rowParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);

TableLayout tableLayout = new TableLayout(context);
tableLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));// assuming the parent view is a LinearLayout

TableRow tableRow = new TableRow(context);
tableRow.setLayoutParams(tableParams);// TableLayout is the parent view

TextView textView = new TextView(context);
textView.setLayoutParams(rowParams);// TableRow is the parent view

tableRow.addView(textView);

説明
を呼び出すときは、親ビューのsetLayoutParamsを渡す必要がありますLayoutParams

于 2012-12-21T10:52:41.877 に答える
6

レイアウト パラメータに TableRowLayout、TableLayout などを指定する必要があることがわかりました。そうしないと、テーブルが表示されません。

于 2009-10-07T01:28:33.120 に答える
1

適切な解決策は、作成する行のインスタンスごとにレイアウト ファイルを拡張することです。この投稿を参照してください:ビューを複製してリストとテーブルにデータを入力する方法は?

于 2014-01-11T06:39:13.757 に答える
0

私にとって、私のものを手に入れるには電話しなければなりませんでしたaddContentView()

于 2012-04-14T04:51:08.307 に答える