我创建了一个带有Button的LinearLayout,我想每次单击该按钮时添加一个新的Textview。这是我编写的代码,但对我不起作用:
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
linearLayout).addView(textView);
}
});
这是xml文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:text="+" />
</LinearLayout>
答案 0 :(得分:0)
在您的按钮onClickListener上,您需要创建新的textview,然后将其添加到LinearLayout中。查看以下StackOverflow:response。链接的线程显示类似的问题。
请注意,如果您想拥有很多这些TextView,则应考虑使用RecyclerView。
答案 1 :(得分:0)
您可以这样做:
((LinearLayout) linearLayout).addView(textView);
其中linearLayout是LinearLayout的ID,textView是TextView的ID。