按钮的 OnClick 更多视图应该在运行时添加到布局中,但我无法做到这一点
我想通过单击按钮添加视图。我的屏幕有一个文本视图、一个编辑文本和一个“添加更多”按钮。单击按钮后,另一组文本视图和编辑文本应附加到屏幕上。我还计划在屏幕变长后添加滚动视图。 我的代码片段如下
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
text.setText("hello how are you?"); //this is just an example, I may want to add lot more here.
linearLayout.addView(text);
setContentView(linearLayout);
}
我知道我缺少一些非常基本的东西,但我不知道那是什么。 :(
请帮忙。
I want to add views on click of button. My screen has a text view and an edit text and a "Add More" button. on the click of button another set of text view and edit text should get appended to the screen. I am also planning to add scroll view once the my screen grows longer.
My Code snippet is as follows
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
text.setText("hello how are you?"); //this is just an example, I may want to add lot more here.
linearLayout.addView(text);
setContentView(linearLayout);
}
I know I am missing something very basic but I do not know what is that. :(
Please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,您需要使用对上下文的引用来初始化每个 TextView。因此,在您的 onClick 中,假设它位于 MyActivity.java 中:
其次,假设您在 onCreate 中调用了 setContentView,这也会将您的 LinearLayout 添加到视图中,因此您不需要每次单击按钮时都调用 setContentView(linearLayout)被点击。
First of all, you need to initialize each TextView with a reference to the context. So, in your onClick, given that it is in MyActivity.java:
Second, given that you have a call to setContentView in onCreate which also adds your linearlayout to the view, you do not need to call setContentView(linearLayout) each time the button is clicked.
您应该首先创建一个新的
TextView
并使用linearLayout.addView()
将EditText
添加到linearLayout
中。无需调用setContentView()
您可能已经添加了它。you should first create a new
TextView
andEditText
add it to thelinearLayout
usinglinearLayout.addView()
. No need to callsetContentView()
you probably already added it.这一个可以帮助你
在你的 XML 文件
和你的 Java 文件中像
}
这只是一个例子,你可以添加任何像这样的视图
This One help you
In your XML file
And your Java file Like
}
This one just example you can add any view like this