title: add dynamic elements to xml on button click android
body: <p>I am trying to add elements dynamically in to the existing xml layout on a button click. Based on the number of times a user clicks on a button, that many items should be added in to the existing xml. I think using the layout inflater is a good technique, but I am not able to do it. Any help will be greatly appreciated.</p>
  
  <p>Thanks! Here is my code:</p>
  
  <p>main.xml:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:id="@+id/main_layout_id"&gt;
  &lt;/LinearLayout&gt;
  </code></pre>
  
  <p>layout_item.xml:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:id="@+id/layout_item_id"&gt;
  
      &lt;Button
          android:id="@+id/button1"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Button" /&gt;
  &lt;/LinearLayout&gt;
  </code></pre>
  
  <p>java file:</p>
  
  <pre><code>public void onCreate(Bundle savedInstanceState)
  {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
  
      final LinearLayout mainLayout = (LinearLayout)findViewById(R.id.main_layout_id);
  
      View view = getLayoutInflater().inflate(R.layout.layout_item, mainLayout,false);
  
      mainLayout.addView(view);
  
      Button b=(Button) findViewById(R.id.button1);
      b.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              Context c=getApplicationContext();
              TextView tvv=new TextView(c);
              tvv.setText("textview");
              mainLayout.addView(tvv);
          }
      }); 
  }
  </code></pre>