I am creating TableLayout
,
xml code of TableLayout
:
<TableLayout
android:id="@+id/productList"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</TableLayout>
I want to add n no of rows dynamically but I want only 2 columns in each row like this image
I have used android:strechColumns
in layout file but not succeed.
how can I solve this problem dynamically.?
Please help...
Thanks in advance.
Here is activity_table_layout_ex xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" >
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TableLayout
android:id="@+id/tableLayoutProduct"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@android:color/white"
android:stretchColumns="*" >
</TableLayout>
</LinearLayout>
</HorizontalScrollView>
</ScrollView>
</LinearLayout>
And here is your activity code:
import android.app.Activity;
import android.os.Bundle;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class TableLayoutEx extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table_layout_ex);
TableLayout tableLayoutProduct = (TableLayout) findViewById(R.id.tableLayoutProduct);
String[] headingTitle = new String[] { "Col1", "Col2", "Col3", "Col4" };
TableRow tableRow = new TableRow(this);
tableRow.setBackgroundColor(getResources().getColor(android.R.color.black));
for (int i = 0; i < headingTitle.length; i++) {
TextView textView = new TextView(this);
textView.setText(headingTitle[i]);
textView.setTextColor(getResources().getColor(android.R.color.white));
textView.setPadding(5, 10, 5, 10);
tableRow.addView(textView);
}
tableLayoutProduct.addView(tableRow);
}
}
Try this working code. You can achieve that by following this example.