动态地向布局中添加元素

7

我对开发应用程序还很陌生。我认为这是一个基本操作,所以如果已经有解决方案的线程,我会接受链接。但是由于我已经搜索了两个小时,仍然没有找到答案,所以我还是要问一下:

我想每次用户点击按钮时动态地向我的布局中添加一个元素。

目前我有以下代码:

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);
    }

由于XML文件不会改变,它只能工作一次。

那么当用户第二次点击按钮时如何添加第二个文本(而不更改XML文件)?可以提供示例。

1个回答

0

问题出在这一行,它每次重新创建整个布局:

LinearLayout ll = new LinearLayout(this);

你应该在 submitChoice 函数之外定义并设置 setContentView(ll)。然后只需在点击时创建和添加 textView,然后调用 ll.invalidate(); 来查看更改。

类似这样:

LinearLayout ll;

protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.game);
            ll = (LinearLayout) findViewById(R.id.ll_game);    
        }

// More code...

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

            ll.addView(textView);
            ll.invalidate();
        }

其中ll_game是您在xml中为LinearLayout设置的id。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接