首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在TableLayout中使用TableLayout时不能理解额外的填充

在TableLayout中使用TableLayout时不能理解额外的填充
EN

Stack Overflow用户
提问于 2014-02-18 22:27:08
回答 1查看 114关注 0票数 0

我正在努力学习如何编写Android程序,而且我很难弄清楚填充是如何工作的,特别是在TableLayout中的一个TableLayout中。

代码语言:javascript
复制
private void fillTable(int nrows, int ncols) {
    final int CENTER = 0x11;  // used for "gravity" parameters
    TableLayout table = (TableLayout) this.findViewById(R.id.tablelayout);
    int counter = 1;
    TextView text;
    for (int i = 0; i < nrows; i++) {
        TableRow row = new TableRow(this);
        table.addView(row);
        for (int j = 0; j < ncols; j++) {
            View cell;
            text = new TextView(this);
            text.setTextColor(Color.BLUE);
            text.setText(Integer.toString(counter++));
            text.setGravity(CENTER);
            if (i == 2 && j == 2) {
                FrameLayout frame = new FrameLayout(this);
                text.setLayoutParams(new FrameLayout.LayoutParams(90, 45, CENTER));
                frame.setPadding(0, 0, 0, 0);
                frame.addView(text);
                cell = frame;
            } else {
                cell = text;
            }
            cell.setBackgroundColor((i + j) % 2 == 0 ? Color.YELLOW : Color.WHITE);
            row.addView(cell);
            cell.setLayoutParams(new TableRow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1F/ncols));
        }
        row.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1F/nrows));
    }
}

tablelayout看起来就像这样:

代码语言:javascript
复制
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tablelayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</TableLayout>

我用nrows=12和ncols=5调用它。我在一个宽度为720像素的仿真器上运行。如果我将if (i==2&&j==2)更改为if (false),以便只显示一个TextView数组,那么正如我所预期的那样,这些列是均匀的。但是,使用编写的代码,中间列比其他列更宽。

我还尝试将android:stretchColumns="*"添加到tablelayout定义中,并从cell.setLayoutParams中删除权重参数,结果是相同的。

假设我有理由要为text.setLayoutParams指定像素(因为我计划稍后做什么),我如何获得相同的列宽?由于90*5很好地低于720,我不明白为什么,或哪里,额外的宽度被增加。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-19 00:22:14

无论何时处理权重,都必须让选项处理剩余的空间。在本例中,宽度。只需将每个元素的宽度设置为0:

代码语言:javascript
复制
cell.setLayoutParams(new TableRow.LayoutParams(0, LayoutParams.MATCH_PARENT, 1F/ncols));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21866829

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档