无法以编程方式在 Android 的 TableLayout 中水平放置所有行

Unable to fit all the rows horizontally in a TableLayout in Android programmatically

我正在创建一个 TableLayout 来动态填充数据。我在这里面临的问题是行没有水平地适合屏幕。 这是我想要的视图,

\-----------------------------------------------------\
\|   Student Name    | Q1 | Q2 | Q3  | Total | % |\
\-----------------------------------------------------\

但问题是,由于 Student Name 是相当大的一行(宽度),其他行不适合屏幕, 它们如下所示,从第 4 季度开始,所有行都不适合屏幕。

\------------------------------------\---------------- 
\|   Student Name    | Q1 | Q2 | Q3  \| Total | % |
\------------------------------------\----------------

这是我用来动态创建此视图的代码

students_table.xml

<ScrollView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scrollbars="none">

    <TableLayout
        android:id="@+id/maintable"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        />
</ScrollView>

QuestionPaperChecking.java

 /** Table Row - Header */
    trHeader = new TableRow(mContext);
    trHeader.setLayoutParams(new TableLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT));

    /* Student name */
    TextView tvStudentName = new TextView(mContext);
    tvStudentName.setText("Student Name");
    tvStudentName.setTextColor(Color.WHITE);
    tvStudentName.setGravity(Gravity.CENTER_VERTICAL);
    tvStudentName.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
    tvStudentName.setBackgroundColor(getColor(mContext, R.color.background_blue_light));
    tvStudentName.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    tvStudentName.setPadding(10, 10, 10, 10);
    trHeader.addView(tvStudentName);

    /* Question 1 */
    TextView tvQ1 = new TextView(mContext);
    tvQ1.setText("Q1");
    tvQ1.setTextColor(Color.WHITE);
    tvQ1.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
    tvQ1.setBackgroundColor(getColor(mContext, R.color.background_blue_light));
    tvQ1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    tvQ1.setPadding(10, 10, 10, 10);
    tvQ1.setGravity(Gravity.CENTER_VERTICAL);
    trHeader.addView(tvQ1);

    //Similarly I have created all other rows

    // Add the TableRow Header to the TableLayout
    tblBattingSide.addView(trHeader, new TableLayout.LayoutParams(
            LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT));

注意:stretchColumns 和 shrinkColumns 不起作用

我假设您希望学生姓名上的文字换行到下一行。

首先要修复的是layout_width。将 ScrollViewlayout_width 值设置为 match_parent/fill_parent。对 header TableRow (trHeader) 以及 table 的每一行执行相同的操作。需要明确的是,TableLayout 上的 layout_width 本身应该保持 match_parent/fill_parent.

这样做是为了确保所有这些视图适合 width-wise 到 parents。这仍然不能完全解决问题,因为行中的视图仍然 "push" 列超出了 table 容器的宽度。

第二步是将TableLayout上的shrinkColumns设置为"1"。这将尽可能缩小第一列,直到 table 适合屏幕(或其容器),并且文本将换行。或者,如果您希望所有列都收缩,您可以将其设置为 "*"