Подтвердить что ты не робот

Как я могу получить Android TableLayout для заполнения экрана?

Я сражаюсь с ужасной системой компоновки Android. Я пытаюсь получить таблицу для заполнения экрана (просто так?), Но это смешно сложно.

Я получил его как-то работать в XML:

<?xml version="1.0" encoding="utf-8"?>

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="fill_parent" android:layout_width="fill_parent">
<TableRow android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_weight="1">
<Button android:text="A" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1"/>
<Button android:text="B" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1"/>
</TableRow>
<TableRow android:layout_height="fill_parent" android:layout_width="fill_parent" android:layout_weight="1">
<Button android:text="C" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1"/>
<Button android:text="D" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_weight="1"/>
</TableRow>

Однако я не могу заставить его работать на Java. Я пробовал миллион комбинаций LayoutParams, но ничего не работает. Это лучший результат, который у меня есть, который заполняет только ширину экрана, а не высоту:

    table = new TableLayout(this);
    // Java. You suck.
    TableLayout.LayoutParams lp = new TableLayout.LayoutParams(
                                    ViewGroup.LayoutParams.FILL_PARENT,
                                    ViewGroup.LayoutParams.FILL_PARENT);
    table.setLayoutParams(lp); // This line has no effect! WHYYYY?!
    table.setStretchAllColumns(true);
    for (int r = 0; r < 2; ++r)
    {
        TableRow row = new TableRow(this);
        for (int c = 0; c < 2; ++c)
        {
            Button btn = new Button(this);
            btn.setText("A");
            row.addView(btn);
        }
        table.addView(row);
    }

Очевидно, что документация на Android не помогает. У кого-нибудь есть идеи?

4b9b3361

Ответ 1

Наконец-то выяснилось, как это сделать. Остановитесь на TableLayout и просто используйте горизонтальную LinearLayout внутри вертикальной. Критический ключ - установить вес. Если вы укажете FILL_PARENT, но с весом по умолчанию, он не работает:

    LinearLayout buttonsView = new LinearLayout(this);
    buttonsView.setOrientation(LinearLayout.VERTICAL);
    for (int r = 0; r < 6; ++r)
    {
        LinearLayout row = new LinearLayout(this);
        row.setOrientation(LinearLayout.HORIZONTAL);
        for (int c = 0; c < 4; ++c)
        {
            Button btn = new Button(this);
            btn.setText("A");
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
            lp.weight = 1.0f;
            row.addView(btn, lp);
        }
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
        lp.weight = 1.0f;
        buttonsView.addView(row, lp);
    }

    ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
    setContentView(buttonsView, lp);

Ответ 2

В приведенном выше обсуждении есть две ошибки.

  • Можно программно установить вес, указав TableLayout.LayoutParams и TableRow.LayoutParams и используя соответствующий конструктор, например.

    TableLayout.LayoutParams rowInTableLp = new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1.0f);

  • Виджет должен иметь LayoutParams своего родителя. Поэтому строки должны использовать TableLayout.LayoutParams

Это дает вам следующую рабочую версию вашего исходного кода:

TableLayout table = new TableLayout(this);
// Java. You succeed!
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
        ViewGroup.LayoutParams.FILL_PARENT,
        ViewGroup.LayoutParams.FILL_PARENT);
table.setLayoutParams(lp);
table.setStretchAllColumns(true);

TableLayout.LayoutParams rowLp = new TableLayout.LayoutParams(
        ViewGroup.LayoutParams.FILL_PARENT,
        ViewGroup.LayoutParams.FILL_PARENT,
        1.0f);
TableRow.LayoutParams cellLp = new TableRow.LayoutParams(
        ViewGroup.LayoutParams.FILL_PARENT,
        ViewGroup.LayoutParams.FILL_PARENT,
        1.0f);
for (int r = 0; r < 2; ++r)
{
    TableRow row = new TableRow(this);
    for (int c = 0; c < 2; ++c)
    {
        Button btn = new Button(this);
        btn.setText("A");
        row.addView(btn, cellLp);
    }
    table.addView(row, rowLp);
}
setContentView(table);

Благодаря Romain Guy на форуме разработчиков Android для решение.

Ответ 4

Вы никогда не устанавливаете параметры макета строки или кнопки, в то время как в размещенном xml вы делаете это. Меняйте детали циклов for, чтобы задать параметры макета строки и параметры макета кнопки, чем это должно дать тот же результат, что и ваш XML.

Ответ 5

Чтобы установить TableLayout LayoutParams, мы логически ожидаем использования класса TableLayout.LayoutParams, но вы получите ошибку приведения, в которой указано, что TableLayout.LayoutParams не могут быть записаны в FrameLayout.LayoutParams.

Итак, вы должны использовать FrameLayout.LayoutParams, если вы хотите программно установить свойства TableLayout. Например:

FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,TableLayout.LayoutParams.MATCH_PARENT);
            layoutParams.setMargins(80, 0, 0, 0);
            TableLayout tableLayout = (TableLayout) findViewById(R.id.header_detail);
            tableLayout.setLayoutParams(layoutParams);