Dynamically add element to layout

Viewed 5248

I am quite new to developing apps. Still I would have thought that this is a basic action, so if there is already a solved thread I would be OK with the link. But since I am searching for over 2 hours for this I am asking anyway:

I want to dynamically add an element to my layout every time the user clicks a button.

By now I have this:

XML (R.layout.game.xml)

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/submit_choice" 
        android:onClick="submitChoice"/>
    </LinearLayout>

Java

  public void submitChoice(View view)
    {
        TextView textView = new TextView(this);
        textView.setTextSize(40);
        textView.setText("text");

        LinearLayout ll = new LinearLayout(this);

        ll.addView(View.inflate(ll.getContext(), R.layout.game, null));
        ll.addView(textView);
        setContentView(ll);
    }

Since the XML file does not change, it only works once.

So how can I add a second text when the user clicks the button a second time (without changing the XML file)? Examples are appreciated.

1 Answers
Related