android - 动态添加元素到布局

标签 android android-layout dynamic

我对开发应用程序还很陌生。我仍然认为这是一个基本操作,所以如果已经有一个已解决的线程,我会接受链接。但是由于我为此搜索了 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>

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 文件)我如何添加第二个文本?示例表示赞赏。

最佳答案

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

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。

关于android - 动态添加元素到布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20844802/

相关文章:

java - 如何在单击列表中父级的特定项目时扩展子级?

具有动态列的 MySQL 数据透视表查询

java - Android 数据绑定(bind)监听器 View

android - 如何带回RelativeLayout?

尝试添加 View 时Android NULL指针异常

javascript - 使用 Javascript 动态添加表格行和单元格

c# - 在单元测试中使用动态

android - 使用 IndoorAtlas 显示 FloorPlan 并获取位置

android - 如何使用 Robotium 从 ListView 中选择两个项目?

android - 只需少量更改即可为同一类的不同版本构建 flavor