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