Skip to content Skip to sidebar Skip to footer

How Do You Add Dynamically A View From Xml File, I Want To Add Tablerow In Relativelayout

I am trying to add table row dynamically in my activity. The table row is in the relative layout. It looks fine but don't know where I am going wrong. Below is my code public void

Solution 1:

It's crashing because that TableRow is already in the layout. If you want to add some dynamically you have to create it programmatically, that is:

// PSEUDOCODETableRownewRow=newTableRow(this);
RelativeLayout.LayoutParamslp=newRelativeLayout.LayoutParams(/*....*/);
newRow.setLayoutParams(lp);

relLayout.add(newRow);

Actually TableRow should be used inside TableLayout.

If you want to use something more than once, you can use the inflate technique. You need to create an xml layout that includes the only part that you want to repeat (so your TableRow and its children), and then:

LayoutInflaterinflater= 
              (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

Viewinflated= inflater.inflate(R.layout.your_layout, null);

Now inflated contains the layout you specified. Instead of null, you might want to put there the layout to which attach the inflated one. Every time you need a new element like that, you would have to inflate it the same way.

(You should always report the error you get when it crashes)

------ EDIT -----

ok now i see, this is your code:

RelativeLayoutRLayout= (RelativeLayout)findViewById(R.id.RelativeLayout);
TableRowtableRow= (TableRow)findViewById(R.id.TableRow);

for(inti=1; i <4; i++) {
    LayoutInflaterinflater= (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    Viewinflated= inflater.inflate(R.layout.main, tableRow);
}

this way you're inflating your whole layout inside the original TableRow.

You should have a row.xml layout like this, together with the main.xml:

<?xml version="1.0" encoding="utf-8"?><TableRowxmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/TableRow"android:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="horizontal"android:layout_alignParentTop="true"android:layout_alignParentLeft="true"
  ><TextViewandroid:id="@+id/Text"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Text"
  /></TableRow>

and then inflate it like this:

RelativeLayoutRLayout= (RelativeLayout)findViewById(R.id.RelativeLayout);

for(inti=1; i <4; i++) {
    LayoutInflaterinflater= (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflater.inflate(R.layout.row, RLayout);
}

see if it works.

Post a Comment for "How Do You Add Dynamically A View From Xml File, I Want To Add Tablerow In Relativelayout"