Thursday 29 September 2011

Add Dynamically Rows or Linear Layout in TableView in android

Here is example that how you can add Rows or LinearLayout Dynamically in TableTayout in android.

Here is java File For My Activity to be stared in application run.


public class DynamicTable extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
        TableLayout mTableLayout=(TableLayout)findViewById(R.id.dynamictable);
        String Fruits[]={"apple","Banana","Mango","Coconut","Graphes","Carrot"};
        String Labels[]={"Fruitname:","Fruitname:","Fruitname:","Fruitname:","Fruitname:","Fruitname:"};
        int i=0;
       // mTableLayout.removeAllViewsInLayout();
        mTableLayout.removeAllViews();
        for(String fruits:Fruits){
         TextView label=new TextView(this);
               TextView value=new TextView(this);
         label.setTextAppearance(this, R.style.textbase);
         value.setTextAppearance(this, R.style.textbase);
         label.setText(Labels[i]);
         value.setText(fruits);
         LinearLayout mLinearLayout=new LinearLayout(this);
         mLinearLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
         mLinearLayout.setOrientation(0);
         mLinearLayout.addView(label);
         mLinearLayout.addView(value);
         mTableLayout.addView(mLinearLayout);
        
        }
   }
}

Now we also need to known what should be in xml for layout screen :
/res/layout/main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TableLayout android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:stretchColumns="1" android:id="@+id/dynamictable"
android:layout_gravity="center">
<TextView android:text="demo" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:text="demo here" android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</TableLayout>

</LinearLayout>


Here is my Emulator OutPut:
Enjoy.........