Статические кнопки под ScrollView с динамическим расположением таблиц внутри

1

У меня есть динамическая таблица, которая может иметь всего 2 строки, но может содержать до 50 строк. Я пытаюсь обернуть эту таблицу в скроллвью. Мне также нужно иметь 2 кнопки, которые должны отображаться внизу страницы.

Вот то, чего я пытаюсь достичь, но я застреваю (приложите изображения, чтобы показать, что я пытаюсь):

  1. Если строк мало, представление прокрутки не должно отображаться, а таблица должна отображаться с кнопками под таблицей.
  2. Если количество строк превышает x, оберните эту таблицу в виде прокрутки с максимальной высотой, а затем покажите кнопки внизу в статическом месте. Таблица прокручивается, но кнопки исчезают под видом прокрутки.

Может кто-нибудь подсказать, что я делаю не так? Я просмотрел много вопросов о StackOverflow, но не смог найти что-то, что решает эту конкретную ситуацию.

Ниже находится мой файл макета, и я заполняю таблицу в упражнении:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ScrollView
        android:id="@+id/sv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TableLayout android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:id="@+id/mainTable">
        </TableLayout>
    </ScrollView>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="425dp"
            android:layout_gravity="center_horizontal"
            android:text="Submit" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_gravity="center_horizontal"
            android:text="Cancel" />
    </LinearLayout>
</LinearLayout>

Изображение 174551

Изображение 174551

Изображение 174551

Изображение 174551

Изображение 174551

Теги:
android-layout
scrollview

2 ответа

2
Лучший ответ

Я хотел бы рассмотреть возможность использования RecyclerView вместо TableLayout в ScrollView. Если вы можете установить статическую высоту для макета вида кнопок, вы можете манипулировать отступами и полями, чтобы получить желаемый эффект. Ниже приведено изменение этого ответа: qaru.site/questions/1244165/...

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ScrollView
        android:id="@+id/sv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:paddingBottom="45dp">
        <TableLayout android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:id="@+id/mainTable">
        </TableLayout>
    </ScrollView>
    <LinearLayout
        android:layout_marginTop="-45dp"
        android:layout_width="wrap_content"
        android:layout_height="45dp"
        android:orientation="horizontal"
        android:layout_gravity="center">
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="Submit" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_gravity="center_horizontal"
            android:text="Cancel" />
    </LinearLayout>
</LinearLayout>
  • 0
    Спасибо @airfish. Я не уверен, как выровнять макет таблицы с представлением реселлера и динамически присоединить его к действию.
  • 0
    Я полагаю, вы могли бы использовать ту же концепцию с вашим TableLayout встроенным в ScrollView вместо RecyclerView выше. ScrollView будет иметь те же свойства, что и RecyclerView а TableLayout останется прежним.
Показать ещё 6 комментариев
0

Спасибо @airfish и @Onik за ваши решения. Решение от @airfish помогло решить мою проблему, после двух последних дней борьбы с ней.

Вот окончательное решение для тех, кто заинтересован в том, чтобы заставить это работать.

Окончательный файл макета.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ScrollView
        android:id="@+id/sv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:paddingBottom="45dp">
        <TableLayout android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:gravity="center_horizontal"
            android:id="@+id/mainTable">
        </TableLayout>
    </ScrollView>
    <LinearLayout
        android:layout_marginTop="-45dp"
        android:layout_width="wrap_content"
        android:layout_height="45dp"
        android:orientation="horizontal"
        android:layout_gravity="center">
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="Submit" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_gravity="center_horizontal"
            android:text="Cancel" />
    </LinearLayout>
</LinearLayout>

MainActivity.java (отредактируйте строку №30, чтобы увеличить/уменьшить количество строк для тестирования)

package com.example.scroll_ex;

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

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TableLayout mainTable = findViewById(R.id.mainTable);

        mainTable.removeAllViews();

        int leftRowMargin = 0;
        int topRowMargin = 0;
        int rightRowMargin = 0;
        int bottomRowMargin = 0;
        int textSize = 0, smallTextSize = 0, mediumTextSize = 0;

        TableRow tr = new TableRow(this);
        TextView column1 = new TextView(this);
        TextView column2 = new TextView(this);

        for(int i=-1; i < 25; i++){

            tr = new TableRow(this);
            column1 = new TextView(this);
            column2 = new TextView(this);

            tr.setGravity(Gravity.CENTER);
            tr.setId(i+ 1);
            TableLayout.LayoutParams trParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
                    TableLayout.LayoutParams.WRAP_CONTENT);
            trParams.setMargins(leftRowMargin, topRowMargin, rightRowMargin, bottomRowMargin);
            tr.setPadding(0,0,0,0);
            tr.setLayoutParams(trParams);

            if (i == -1) {
                column1.setText("Name");
                column1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                        TableRow.LayoutParams.MATCH_PARENT));
                column1.setPadding(5, 5, 1, 5);
            } else {
                column1.setText("Name #" + i);
                column1.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                        TableRow.LayoutParams.WRAP_CONTENT));
                column1.setPadding(5, 0, 1, 5);
            }

            tr.addView(column1);


            if (i == -1) {
                column2.setText("Address");
                column2.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                        TableRow.LayoutParams.MATCH_PARENT));
                column2.setPadding(5, 5, 1, 5);
            } else {
                column2.setText("Address " + i);
                column2.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
                        TableRow.LayoutParams.WRAP_CONTENT));
                column2.setPadding(5, 0, 1, 5);
            }

            tr.addView(column2);
            mainTable.addView(tr, trParams);
        }

    }
}

Изображение 174551

Изображение 174551

Ещё вопросы

Сообщество Overcoder
Наверх
Меню