How do you add dynamically a view from xml file, I want to add TableRow in RelativeLayout

前端 未结 1 454
花落未央
花落未央 2021-01-01 08:01

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

相关标签:
1条回答
  • 2021-01-01 08:09

    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:

    // PSEUDOCODE
    TableRow newRow = new TableRow(this);
    RelativeLayout.LayoutParams lp = new RelativeLayout.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:

    LayoutInflater inflater = 
                  (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    
    View inflated = 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:

    RelativeLayout RLayout = (RelativeLayout)findViewById(R.id.RelativeLayout);
    TableRow tableRow = (TableRow)findViewById(R.id.TableRow);
    
    for(int i = 1; i <4; i++) {
        LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View inflated = 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"?>
    <TableRow xmlns: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"
      >
      <TextView
      android:id="@+id/Text"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Text"
      />
      </TableRow>
    

    and then inflate it like this:

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

    see if it works.

    0 讨论(0)
提交回复
热议问题