Search code examples
javaandroidbuttontextview

How to add a new Textview evertime Button is clicked


I created a LinearLayout with a Button and I want to add a new Textview everytime the button is clicked. This is the code I wrote but it does not work for me:

btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            linearLayout).addView(textView);


            }
        });

and this is the xml file:

<?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>

Solution

  • In Your button onClickListener You need to create new textview and then add it to Your LinearLayout. Look at this StackOverflow: response. Linked thread shows similar problem.
    Be aware that if You want to have a lot of those TextViews, then You should consider using RecyclerView.