简体   繁体   English

在TableRow中设置边距和背景色

[英]Setting margin AND background color in a TableRow

I have a strange issue when setting programmatically both margin and background color on a TableRow. 以编程方式在TableRow上设置边距背景颜色时,我遇到一个奇怪的问题。 I already read this thread about margin, and this one about background color, but apparently, I do things correctly. 我已经看过这个线程约保证金,并且这其中约背景颜色,但显然,我做正确的事情。 The problem seems to be somewhere else. 问题似乎出在其他地方。

I create dynamically TableRows, which odds must be a specific color (to improve readability). 我动态创建TableRows,赔率必须是特定的颜色(以提高可读性)。 I simply wrote this : 我只是这样写:

if(myCursor != null && myCursor.moveToFirst()){
do{
    TableRow tableRow = new TableRow(getActivity());
    TableLayout.LayoutParams tlp = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT);
    tlp.setMargins(0, 10, 0, 10);
    tableRow.setLayoutParams(tlp);

    for(int j=0 ; j < TopTagsDetailsCursor.getColumnCount();j++){
        TextView tv = new TextView(getActivity());
        tv.setText(TopTagsDetailsCursor.getString(j));
        if (j>0) tv.setGravity(Gravity.CENTER);
        tableRow.addView(tv);                       
    }

    if ((i % 2) != 0){
        tableRow.setBackgroundColor(getResources().getColor(R.color.table_row));
    }

    dataTable.addView(tableRow);
    i++;
});
}while(myCursor.moveToNext());

What I don't understand, is that on each odd row, with my custom background color, my custom margins (10 for top and bottom) aren't "applied" to the row, but they do are on even row. 我不明白的是,在具有我自定义背景色的每个奇数行上,我的自定义边距(顶部和底部的10)没有“应用”到该行,但确实在偶数行上。 Still stranger: if I remove the part of the code about custom background color, margins are OK everywhere !! 仍然很陌生:如果我删除代码中有关自定义背景色的部分,则在任何地方都可以使用边距!

So, why my custom margins aren't ok when I put custom background color ?? 所以, 为什么当我放入自定义背景色时我的自定义边距不正确?

PS: I even tried to move some lines of code (especially the addView(tableRow) and those about the color), but no effect. PS:我什至尝试移动一些代码行(特别是addView(tableRow)和有关颜色的代码),但没有效果。

Thanks in advance ! 提前致谢 ! :) :)

It doesn't explain why it didn't work before, but at least I finally found a "fix". 它没有解释为什么以前不起作用,但是至少我终于找到了一个“解决方案”。 I remove these lines : 我删除这些行:

TableLayout.LayoutParams tlp = new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT);
tlp.setMargins(0, 10, 0, 10);
tableRow.setLayoutParams(tlp);

And I replaced : 我替换了:

tableRow.addView(tv);

by : 创建人:

tableRow.addView(tv, new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, 80)); //or any other value

and it works fine finally... even if I don't understand why my first solution didn't work :) (feel free to explain me why !) 并且最终效果很好...即使我不明白为什么我的第一个解决方案不起作用:) (随时向我解释原因!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM