Пользовательский TableLayout с несколькими TextViews в строках - PullRequest
4 голосов
/ 18 декабря 2011

Я хочу создать собственную таблицу TableLayout с такими строками:

TV для TextView, т.е. я хочу добавить 11 TextViews в строку:

enter image description here

Каждая строка начинается с заголовка, а затем я добавляю 5 пар TextViews, чтобы строка таблицы была такой же широкой, как и экран. Вот мой код:

public class FlowTable extends TableLayout {

    private Context context;

    public FlowTable(Context context) {
        super(context);
        this.context = context;
    }

    public FlowTable(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }

    public void addContent(List<ResultItem> data) {

        TableRow tableRow = new TableRow(context);

        LayoutParams params = new LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1);

        for (int i = 0; i < data.size(); i++) {

            if (i % 5 == 0) {
                this.addView(tableRow, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

                tableRow = new TableRow(context);
                TextView tvRange = new TextView(context);
                tvRange.setLayoutParams(params);
                tvRange.setText(genRange(i+1));
                tableRow.addView(tvRange);

            }
            TextView tvDistance = new TextView(context);
            tvDistance.setLayoutParams(params);
            tvDistance.setText(String.valueOf(data.get(i).distance));

            TextView tvResult = new TextView(context);
            tvResult.setLayoutParams(params);
            tvResult.setText(data.get(i).result);

            tableRow.addView(tvDistance);
            tableRow.addView(tvResult);
        }
    }

    private String genRange(int currIndex){
        /********************/
        return somestring;
    }
}

Использование таблицы:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <packagename.FlowTable
        android:id="@+id/flowTable"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

Во фрагменте:

View root = inflater.inflate(R.layout.fragment_session_summary, container, false);
        FlowTable flowTable = (FlowTable)root.findViewById(R.id.flowTable);
        flowTable.addContent(data);

Проблема: экран просто пустой!Вообще ничегоДо того, как я добавил параметры макета в textview, он работал, но строка не занимала ширину экрана.Мое первоначальное решение было основано на примерах LinearLayout, потому что TableRow является расширением LinearLayout.Но я не могу заставить это работать.Спасибо.

Ответы [ 2 ]

10 голосов
/ 27 декабря 2011

Попробуйте программно настроить растяжение всех столбцов (мне кажется, не работает в XML):

...
flowTable.addContent(data);
flowTable.setStretchAllColumns(true);

Некоторые другие быстрые факты:

  • Не нужно пытатьсяи укажите высоту и ширину для TableRow в TableLayout , потому что это всегда будет высота = WRAP_CONTENT и ширина = MATCH_PARENT.См. документацию TableLayout , где это указано в разделе "Обзор классов"
  • Нет необходимости пытаться указать высоту и виджет для детей TableRow , поскольку они всегда будут высотой =WRAP_CONTENT и width = MATCH_PARENT.См. документацию TableRow , где это указано в разделе "Обзор классов"

Могу ли я также смиренно предложить немного рефакторинга:

public class FlowTable extends TableLayout {
    private TableRow mCurrentRow;

    public FlowTable(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public FlowTable(Context context) {
        super(context);
        init();
    }

    private void init() {
        mCurrentRow = new TableRow(getContext());
        mCurrentRow.addView(createAndFillTextView("0")); // title for first row
        setStretchAllColumns(true);
    }

    public void addContent(List<ResultInfo> data) {
        for (int i = 0; i < data.size(); i++) {
            if ((i % 5 == 0) && (i != 0) /** Don't do this on 0! */) {
                finishRowAndStartNew(i);
            }

            mCurrentRow.addView(createAndFillTextView(data.get(i).distance));
            mCurrentRow.addView(createAndFillTextView(data.get(i).result));
        }
    }

    private void finishRowAndStartNew(int newRowIndex) {
        addView(mCurrentRow);
        mCurrentRow = new TableRow(getContext());
        mCurrentRow.addView(createAndFillTextView(genRange(newRowIndex+1)));
    }

    private String genRange(int currIndex){
        /********************/
        return String.valueOf(currIndex);
    }

    private TextView createAndFillTextView(String text) {
        TextView tv = new TextView(getContext());
        tv.setText(text);        
        return tv;
    }
}
1 голос
/ 27 декабря 2011

Если вы хотите использовать для этого XML-макет, попробуйте следующее:

    <TableLayout
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="wrap_content" android:layout_height="wrap_content">
                <TableRow android:weightSum="1">
                    <LinearLayout android:layout_height="wrap_content" android:orientation="horizontal"
                        android:layout_width="wrap_content" android:layout_weight="1" android:layout_marginRight="4dp">
                        <TextView android:id="@+id/totalText"
                            android:layout_height="wrap_content" android:layout_width="wrap_content"
                            android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                            android:text="Title" android:layout_weight="1"/>
                    </LinearLayout>
                    <!-- First Group -->
                    <LinearLayout android:layout_height="wrap_content" android:orientation="horizontal"
                        android:layout_width="wrap_content" android:layout_weight="1" android:layout_marginRight="4dp">

                        <TextView android:id="@+id/totalText"
                                android:layout_height="wrap_content" android:layout_width="wrap_content"
                                android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                                android:text="Tv1"/>
                        <TextView android:id="@+id/totalText"
                                android:layout_height="wrap_content" android:layout_width="wrap_content"
                                android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                                android:text="Tv2"/>
                    </LinearLayout>
                    <!-- Second Group -->
                    <LinearLayout android:layout_height="wrap_content" android:orientation="horizontal"
                        android:layout_width="wrap_content" android:layout_weight="1" android:layout_marginRight="4dp">
                        <TextView android:id="@+id/totalText" 
                                android:layout_height="wrap_content" android:layout_width="wrap_content"
                                android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                                android:text="Tv1"/>
                        <TextView android:id="@+id/totalText" 
                                android:layout_height="wrap_content" android:layout_width="wrap_content"
                                android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                                android:text="Tv2"/>
                    </LinearLayout>


                    <!-- Third Group -->
                    <LinearLayout android:layout_height="wrap_content" android:orientation="horizontal"
                        android:layout_width="wrap_content" android:layout_weight="1" android:layout_marginRight="4dp">
                        <TextView android:id="@+id/totalText" 
                                android:layout_height="wrap_content" android:layout_width="wrap_content"
                                android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                                android:text="Tv1"/>
                        <TextView android:id="@+id/totalText" 
                                android:layout_height="wrap_content" android:layout_width="wrap_content"
                                android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                                android:text="Tv2"/>
                    </LinearLayout>

                    <!-- Fourth Group -->
                    <LinearLayout android:layout_height="wrap_content" android:orientation="horizontal"
                        android:layout_width="wrap_content" android:layout_weight="1" android:layout_marginRight="4dp">

                        <TextView android:id="@+id/totalText"
                                android:layout_height="wrap_content" android:layout_width="wrap_content"
                                android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                                android:text="Tv1"/>
                        <TextView android:id="@+id/totalText"
                                android:layout_height="wrap_content" android:layout_width="wrap_content"
                                android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                                android:text="Tv2" />
                    </LinearLayout>
                    <!-- Fifth Group -->
                    <LinearLayout android:layout_height="wrap_content" android:orientation="horizontal"
                        android:layout_width="wrap_content" android:layout_weight="1" android:layout_marginRight="2dp">

                        <TextView android:id="@+id/totalText" 
                                android:layout_height="wrap_content" android:layout_width="wrap_content"
                                android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                                android:text="Tv1"/>
                        <TextView android:id="@+id/totalText" 
                                android:layout_height="wrap_content" android:layout_width="wrap_content"
                                android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                                android:text="Tv2"/>
                    </LinearLayout>
                </TableRow>
                <TableRow android:weightSum="1">
                    <LinearLayout android:layout_height="wrap_content" android:orientation="horizontal"
                        android:layout_width="wrap_content" android:layout_weight="1" android:layout_marginRight="4dp">
                        <TextView android:id="@+id/totalText"
                            android:layout_height="wrap_content" android:layout_width="wrap_content"
                            android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                            android:text="Title" android:layout_weight="1"/>
                    </LinearLayout>
                    <!-- First Group -->
                    <LinearLayout android:layout_height="wrap_content" android:orientation="horizontal"
                        android:layout_width="wrap_content" android:layout_weight="1" android:layout_marginRight="4dp">

                        <TextView android:id="@+id/totalText"
                                android:layout_height="wrap_content" android:layout_width="wrap_content"
                                android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                                android:text="Tv1"/>
                        <TextView android:id="@+id/totalText"
                                android:layout_height="wrap_content" android:layout_width="wrap_content"
                                android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                                android:text="Tv2"/>
                    </LinearLayout>
                    <!-- Second Group -->
                    <LinearLayout android:layout_height="wrap_content" android:orientation="horizontal"
                        android:layout_width="wrap_content" android:layout_weight="1" android:layout_marginRight="4dp">
                        <TextView android:id="@+id/totalText" 
                                android:layout_height="wrap_content" android:layout_width="wrap_content"
                                android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                                android:text="Tv1"/>
                        <TextView android:id="@+id/totalText" 
                                android:layout_height="wrap_content" android:layout_width="wrap_content"
                                android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                                android:text="Tv2"/>
                    </LinearLayout>


                    <!-- Third Group -->
                    <LinearLayout android:layout_height="wrap_content" android:orientation="horizontal"
                        android:layout_width="wrap_content" android:layout_weight="1" android:layout_marginRight="4dp">
                        <TextView android:id="@+id/totalText" 
                                android:layout_height="wrap_content" android:layout_width="wrap_content"
                                android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                                android:text="Tv1"/>
                        <TextView android:id="@+id/totalText" 
                                android:layout_height="wrap_content" android:layout_width="wrap_content"
                                android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                                android:text="Tv2"/>
                    </LinearLayout>

                    <!-- Fourth Group -->
                    <LinearLayout android:layout_height="wrap_content" android:orientation="horizontal"
                        android:layout_width="wrap_content" android:layout_weight="1" android:layout_marginRight="4dp">

                        <TextView android:id="@+id/totalText"
                                android:layout_height="wrap_content" android:layout_width="wrap_content"
                                android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                                android:text="Tv1"/>
                        <TextView android:id="@+id/totalText"
                                android:layout_height="wrap_content" android:layout_width="wrap_content"
                                android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                                android:text="Tv2" />
                    </LinearLayout>
                    <!-- Fifth Group -->
                    <LinearLayout android:layout_height="wrap_content" android:orientation="horizontal"
                        android:layout_width="wrap_content" android:layout_weight="1" android:layout_marginRight="2dp">

                        <TextView android:id="@+id/totalText" 
                                android:layout_height="wrap_content" android:layout_width="wrap_content"
                                android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                                android:text="Tv1"/>
                        <TextView android:id="@+id/totalText" 
                                android:layout_height="wrap_content" android:layout_width="wrap_content"
                                android:textStyle="bold" android:textSize="12sp" android:textColor="#000000"
                                android:text="Tv2"/>
                    </LinearLayout>
                </TableRow>
</TableLayout>

Надеюсь, это поможет вам. , , И если вы хотите другой, то XML, тогда дайте мне знать. Спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...