Search code examples
javaandroidtablelayoutcolumn-width

TableLayout in Android Development


I am having issues in TableLayout, width issues. I tried searching a lot, but all I get is solution using xml. I am doing it programmatically. Here is what I am doing

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    TableLayout table = new TableLayout(this);
    table.setStretchAllColumns(true);
    table.setShrinkAllColumns(true);


    TableRow tableTitle = new TableRow(this);
    tableTitle.setGravity(Gravity.CENTER_HORIZONTAL);

    TableRow name = new TableRow(this);
    TableRow password = new TableRow(this);
    TableRow button = new TableRow(this);

    TextView empty = new TextView(this);

    TextView title = new TextView(this);
    title.setText("Hello table layout");
    title.setGravity(Gravity.CENTER_HORIZONTAL);

    TextView txtUname = new TextView(this);
    txtUname.setText("Username");

    TextView txtPass = new TextView(this);
    txtPass.setText("Password");


    EditText uname = new EditText(this);
    EditText pass  = new EditText(this);

    Button login = new Button(this);
    login.setText("Login");

    name.addView(txtUname);
    name.addView(uname);

    password.addView(txtPass);
    password.addView(pass);

    button.addView(empty);
    button.addView(login);

    table.addView(name);
    table.addView(password);
    table.addView(button);

    table.setColumnShrinkable(0, true); 

    setContentView(table);
}

I want to shrink first column. What should I add in this code?

Anyone help!


Solution

  • You should consider moving your to layout xml file. This would make your life way easier.

    To make only first column shrinkable replace setShrinkAllColumns(true) with setColumnShrinkable(0, true).