如何添加一个新的 Textview evertime Button is clicked
How to add a new Textview evertime Button is clicked
我创建了一个带有按钮的 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>
在您的按钮 onClickListener 中,您需要创建新的 textview,然后将其添加到您的 LinearLayout。看看这个 Whosebug:response。链接的线程显示了类似的问题。
请注意,如果你想拥有很多这样的 TextView,那么你应该考虑使用 RecyclerView。
你可以这样做:
((LinearLayout) linearLayout).addView(textView);
其中 linearLayout 是您的 LinearLayout 的 ID,textView 是您的 TextView 的 ID。
我创建了一个带有按钮的 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>
在您的按钮 onClickListener 中,您需要创建新的 textview,然后将其添加到您的 LinearLayout。看看这个 Whosebug:response。链接的线程显示了类似的问题。
请注意,如果你想拥有很多这样的 TextView,那么你应该考虑使用 RecyclerView。
你可以这样做:
((LinearLayout) linearLayout).addView(textView);
其中 linearLayout 是您的 LinearLayout 的 ID,textView 是您的 TextView 的 ID。