动态textView Android中的边距

时间:2014-04-22 16:10:07

标签: android textview margin

我正在尝试动态创建一个textview。

    int N=5;
    TableRow row = (TableRow) findViewById(R.id.tableRow1);
    final TextView[] myTextViews = new TextView[N];

    for (int i = 0; i < N; i++) {
        // create a new textview
        final TextView rowTextView = new TextView(this);

        //set the format
        rowTextView.setWidth(50);
        rowTextView.setHeight(50);
        rowTextView.setBackgroundColor(Color.GREEN);
        rowTextView.setp
        rowTextView.setPadding(2, 2, 2, 2);

        // set some properties of rowTextView or something
        rowTextView.setText("this is row #" + i);

        // add the textview to the linearlayout
        row.addView(rowTextView);

        // save a reference to the textview for later
        myTextViews[i] = rowTextView;
    }

我试图为每个textView提供一点差距或余量

        rowTextView.setPadding(2, 2, 2, 2);

但是,填充文本与textview之间存在间隙,而不是每个textView之间的差距

任何人都知道如何在2个textview之间留出余量或差距?

感谢

2 个答案:

答案 0 :(得分:1)

您可以尝试在每两个TextView之间添加一个空TextView:

int N=5;
TableRow row = (TableRow) findViewById(R.id.tableRow1);
final TextView[] myTextViews = new TextView[2 * N];

for (int i = 0; i < 2 * N; i++) {
    // create a new textview
    final TextView rowTextView = new TextView(this);

    //set the format
    rowTextView.setBackgroundColor(Color.GREEN);
    rowTextView.setWidth(50);

    if (i % 2 == 0) {
        rowTextView.setHeight(50);

        // set some properties of rowTextView or something
        rowTextView.setText("this is row #" + i / 2);
    }
    else {
        // set the space between 2 rows
        rowTextView.setHeight(2);
    }

    // add the textview to the linearlayout
    row.addView(rowTextView);

    // save a reference to the textview for later
    myTextViews[i] = rowTextView;
}

答案 1 :(得分:0)

您要找的是margins而不是padding。做这样的事情:

TextView tv = new TextView();
....

LinearLayout.LayoutParams tvlp = (LinearLayout.LayoutParams) tv.getLayoutParams();
tvlp.rightMargin = 5;
tvlp.leftMargin = 5;
tvlp.topMargin = 5;
tvlp.bottomMargin = 5;