动态添加元素到布局

Ric*_*ano 5 android dynamic android-layout

我对开发应用程序很陌生。我仍然认为这是一个基本操作,所以如果已经有一个已解决的线程,我可以使用链接。但由于我为此搜索了 2 个多小时,所以我还是要问:

每次用户单击按钮时,我都想动态地将一个元素添加到我的布局中。

现在我有这个:

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>
Run Code Online (Sandbox Code Playgroud)

爪哇

  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);
    }
Run Code Online (Sandbox Code Playgroud)

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

那么如何在用户第二次单击按钮时添加第二个文本(不更改 XML 文件)?示例表示赞赏。

Adi*_*nia 0

问题来自这一行,每次都重新创建整个布局:

LinearLayout ll = new LinearLayout(this);
Run Code Online (Sandbox Code Playgroud)

setContentView(ll)您应该在函数外部定义它submitChoice。然后单击仅创建并添加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();
        }
Run Code Online (Sandbox Code Playgroud)

ll_game您必须在 xml 中为您的LinearLayout.