segFault
segFault

Reputation: 1228

TableLayout not centering

Here is my xml:

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/test"
android:layout_width="fill_parent"
android:layout_height="fill_parent" 
android:gravity="center" >
<TableRow
    android:id="@+id/tableRow1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    >
    <TextView
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />
    <TextView
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />
</TableRow>

I generate the rest dynamically.

Right now it centers it horizontally on the screen but everything is on the left side. I know its a simple fix but I can't seem to get it right.

Here is my manual code:

for(Item l : leaders)
    {
        // Make a new row
        TableRow row = new TableRow(this);
        row.setBackgroundColor(Color.DKGRAY);

        TextView name= new TextView(this);
        TextView score = new TextView(this);

        createView(row, name, l.getName());
        createView(row, score, String.valueOf(l.getScore()));

        name.setTextColor(Color.MAGENTA); // Just to distinguish between the columns
        // Add row to table layout
        tl.addView(row);
    }
}

private void createView(TableRow row, TextView textView, String string)
{
    textView.setText(string);
    textView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    textView.setTextColor(Color.CYAN);
    textView.setTextSize(32);
    textView.setPadding(20, 0, 0, 0);
    row.setPadding(0, 1, 0, 1);
    row.addView(textView);
}

Also, the given answers didn't change the layout.

Upvotes: 0

Views: 942

Answers (3)

Bevor
Bevor

Reputation: 8605

If anybody has the same problem, the trick is to set

android:stretchColumns="0"

in the TableLayout and

android:layout_gravity="center"

android:layout_width="match_parent"

within the content views inside the rows.

Upvotes: 1

Hardik Gajjar
Hardik Gajjar

Reputation: 5058

and you can ad the layoutGravity Centre for Table Layout set in center in parrent Layouts as

android:layout_gravity="center"

you can set the Gravity Centre

myTableLayout.setGravity(Gravity.CENTER);

Upvotes: 0

himanshu
himanshu

Reputation: 1980

I think u should write android:layout_gravity="center" in table layout instead of android:gravity="center".

Upvotes: 0

Related Questions