Question

I'm trying to create a textview dynamically.

    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;
    }

I'm trying to give a little gap or margin for each textView

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

however, the padding gave a gap between the text with the textview instead of the gap between each textView

anyone know how to give a margin or gap between 2 textview?

thanks

Was it helpful?

Solution 2

What you're looking for are margins instead of padding. Just do something like this:

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

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

OTHER TIPS

You could try to add an empty TextView between every 2 TextViews:

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top