sarakinos
sarakinos

Reputation: 686

How to populate the same view with layout inflater?

I have a layout and every time my button is pressed I want to add a group of views stored in another layout. This is the way I tried it so far. The error in logcat is:

"E/AndroidRuntime(7900): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first."

Code:

material_cost.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

       
</LinearLayout>
</ScrollView>

material_cost_item.xml

<?xml version="1.0" encoding="utf-8"?>
    

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/materialItem"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

    </LinearLayout>
  

And finally my class:

public class MaterialActivity extends Activity implements OnClickListener {

    Button btnAdd;
    LinearLayout rootLayout;
    View layoutItem;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.material_cost);
        
        btnAdd = (Button) findViewById(R.id.btnMaterialAdd);
        

        rootLayout = (LinearLayout) findViewById(R.id.materialWrapper);
        layoutItem = getLayoutInflater().inflate(R.layout.material_cost_item, rootLayout,false);
        rootLayout.addView(layoutItem);

        btnAdd.setOnClickListener(this);
    }
    
    public void onClick(View v){
        
        switch (v.getId()){
        case R.id.btnMaterialAdd:{
            inflateEntry();
            break;
        }
        }
    }

    private void inflateEntry() {
        // TODO Auto-generated method stub
        Log.v("debug","pressed");
        rootLayout.addView(layoutItem); 
    }
}

Upvotes: 0

Views: 1006

Answers (1)

moh.sukhni
moh.sukhni

Reputation: 2230

you need to inflate the view again every time you click the button:

private void inflateEntry() 
{
    // TODO Auto-generated method stub
    Log.v("debug","pressed");
    View layoutItem = getLayoutInflater().inflate(R.layout.material_cost_item, null);
    rootLayout.addView(layoutItem); 
}

Upvotes: 1

Related Questions