0

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>
  • Make a recyclerview and with every click add one item to it – MMG Apr 15 '20 at 17:14
  • 1
    check this https://stackoverflow.com/questions/3204852/how-to-add-a-textview-to-linearlayout-in-android – Tiko Apr 15 '20 at 17:15

2 Answers2

0

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.

Community
  • 1
  • 1
OMIsie11
  • 459
  • 5
  • 19
  • Please describe what You did and what is not working. Did You added ID to LinearLayout and then added TextView to it? 'linearLayout.addView(textView);' This snippet adds TextView named textview (constructed like this: TextView textView = new TextView(this);) to LinearLayout named 'linearLayout'. You need to find Your LinearLayout by its id attribute using findViewById() – OMIsie11 Apr 15 '20 at 17:29
  • Thank you the link in the response was very helpful. –  Apr 16 '20 at 11:53
0

you can do it like this :

((LinearLayout) linearLayout).addView(textView);

Where linearLayout is the id of your LinearLayout and textView the id of your TextView.

Nicolas Nicolas
  • 293
  • 1
  • 3
  • 10