1

So I have a snippet of code where I create a textView on a user's click on a button. Since it was created after runtime I'm unsure what the ID is. But what I'm trying to do is have the option of deleting the last textView that is added and also clear all of the TextViews that were added. Thank you

private TextView createNewTextView(String text)
    {
        ArraySize++;
        final LinearLayout mLayout=findViewById(R.id.linearLayout);
        String newLine=System.getProperty("line.separator");
        final LinearLayout.LayoutParams lparams =new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        ViewGroup.LayoutParams params=(RelativeLayout.LayoutParams) mLayout.getLayoutParams();
        final TextView textView=new TextView(this);
        textView.setLayoutParams(lparams);
        textView.setText("New texT:: "+text+newLine);
        listOfNames.add(text);
        return textView;
    }

5 Answers5

1

you could create a XML File in this path res/values/ids.xml;

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="view_1" type="id"/>
</resources>

then in Java you add the id, like this

textView.setId(R.id.view_1);

and when you want to remove it

LinearLayout mLayout=findViewById(R.id.linearLayout);//to find in this specific view
TextView textView = (TextView)mLayout.findViewById(R.id.view_1);
mLayout.removeView(textView);
Edgar
  • 43
  • 1
  • 6
1

You use removeViewAt with the index

final LinearLayout mLayout=findViewById(R.id.linearLayout)
mLayout.removeViewAt(mLayout.getChildCount()-1); // get the last view

//or using index counter variable
//mLayout.removeViewAt(ArraySize-1); // adjust the value accordingly

or you can fetch the view and remove it using removeView

final LinearLayout mLayout=findViewById(R.id.linearLayout)
View v = mLayout.getChildAt(mLayout.getChildCount()-1);
mLayout.removeView(v);
Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68
0

As mentioned in this question, you can simply use

((ViewGroup) textView.getParent()).removeView(textView);
Logan
  • 92
  • 8
0

To remove all views:

mLayout.removeAllViews();

To remove last TextView:

mLayout.removeView(mLayout.getChildAt(mLayout.getChildCount()-1));
nupadhyaya
  • 1,909
  • 1
  • 14
  • 14
0

You can give an Id as edgar mentions or use the View.setTag , you can then find views by tag using viewGroup.findViewWithTag.

htafoya
  • 18,261
  • 11
  • 80
  • 104