Search code examples
androidlayoutpaddinggravity

Programmatic Layout with SetPadding and SetGravity


I am trying to duplicate the following layout programmatically; however, the setGravity and setPadding don't seem to have an effect:

I'm trying to recreate the textviews within the TableRows (note that there's padding and the second text view is right aligned). Also, I'm trying to recreate additional entries because they are dynamic:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android" 
        android:id="@+id/myinfo_root"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:scrollbars="vertical"
        >
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainTable"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:stretchColumns="1">

    <TableRow>
        <TextView
            android:layout_column="1"
            android:text="Text1"
            android:padding="3dip" />

        <TextView
            android:id="@+id/text1"
            android:text="TBD"
            android:gravity="right"
            android:padding="3dip" />
    </TableRow>
    <TableRow>
        <TextView
            android:layout_column="1"
            android:text="Text2"
            android:padding="3dip" />

        <TextView
            android:id="@+id/text2"
            android:text="TBD"
            android:gravity="right"
            android:padding="3dip" />
    </TableRow>
    . . .

Here's a code snippet to add the TextViews. It seems to work but the entries don't have padding and are not right aligned.

    int n = 0;
    TableLayout table = (TableLayout) findViewById(R.id.mainTable);

    for (int j=0; j<2; j++) {
        Log.v(LOG_TAG, "entering for loop");
        n++;

        TableRow tr = new TableRow(getApplicationContext());
        tr.setId(100+n);

        String key = "hello";
        float value = (float) 1.388);
        value = value/3600;

        TextView tvDynamicKey = new TextView(getApplicationContext());                      
        TextView tvDynamicUnit = new TextView(getApplicationContext());

        tvDynamicUnit.setText(Float.toString(value));
        tvDynamicUnit.setGravity(Gravity.RIGHT);
        tvDynamicKey.setText(key + " " + n); 
        tvDynamicKey.setPadding(3, 3, 3, 3);
        tvDynamicUnit.setPadding(3, 3, 3, 3);
        tr.addView(tvDynamicKey);
        tr.addView(tvDynamicUnit);
        table.addView(tr);
    }    
  }

Solution

  • In your layout you always specify column1 for the left element (android:layout_column="1"). But you don't do it programmatically for the dynamic creation. You can do it like this. I tested it, it works on my environment.

     tvDynamicKey.setLayoutParams(new TableRow.LayoutParams(1));