0

How do you convert the xml below to java code in an activity?...

    <TableRow android:background="#00ff00" android:layout_margin="2dip">
        <TextView android:id="@+id/firstview"  android:layout_margin="2dip"/>
        <TextView android:id="@+id/someview"  android:layout_margin="2dip"/>

    </TableRow>

this is an example taken from http://www.droidnova.com/display-borders-in-tablelayout,112.html

stema
  • 90,351
  • 20
  • 107
  • 135
khan
  • 343
  • 1
  • 7
  • 17
  • Just to confirm, this TableRow will be a child of a TableLayout and you just want to be able to add the views programmatically, correct? – Noel Jun 12 '11 at 15:21
  • correct, my tablelayout will be declared in XML, but tablerows will need to be created dynamically. =) – khan Jun 12 '11 at 16:10
  • in java code i have TableLayout table = (TableLayout) findViewById(R.id.TableLayout01);...................table.addView(row, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); – khan Jun 12 '11 at 16:12
  • I know I need something like LinearLayout.LayoutParams lp = new LinearLayout.LayoutParam, but I just can't get it right...when I do row.addView(someView, lp) the someView does not display...thanks – khan Jun 12 '11 at 16:14

2 Answers2

0

From the documentation for TableLayout

The children of a TableLayout cannot specify the layout_width attribute. Width is always MATCH_PARENT. However, the layout_height attribute can be defined by a child; default value is WRAP_CONTENT. If the child is a TableRow, then the height is always WRAP_CONTENT.

Try updating your LayoutParams to use MATCH_PARENT, WRAP_CONTENT for the width and height respectively.

Noel
  • 7,350
  • 1
  • 36
  • 26
  • I can't compile with MATCH_PARENT...I got the code from http://huuah.com/using-tablelayout-on-android/ this part of it seems to work correctly – khan Jun 12 '11 at 16:26
  • Try FILL_PARENT. MATCH_PARENT was added in API 8 to replace FILL_PARENT – Noel Jun 12 '11 at 16:28
  • I think its the way I am declaring layout_margin in TableRow and TextView. So I think if I can some how convert that XML on top to java code it will work... – khan Jun 12 '11 at 16:28
  • That's okay :) Just use FILL_PARENT instead of MATCH_PARENT. It should work the same. – Noel Jun 12 '11 at 16:37
0

Give an id to TableRow in xml files, for example, myRow

Java code:

TableRow tr = (TableRow)this.findViewById(R.id.myRow);

TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);

lp.setMargins(4, 4, 4, 4);

TextView tv1 = new TextView(this);
tr.addView(tv1, lp);

TextView tv2 = new TextView(this);
tr.addView(tv2, lp);

in that way, you could set the margin.

en, setMargins using px, you should changed 2dip into px yourself.

I come here for asking the same question, and i get answer from this title: How to set margin of ImageView using code, not xml

Community
  • 1
  • 1
wolfkin
  • 31
  • 5