Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having a problem removing TextViews from a LinearLayout programmatically

I am programmatically adding TextViews to a LinearLayout, and deleting them on touch. It all works fine except when the last TextView is touched it doesn't get removed. If I do anything else on the screen like get rid of the keyboard or scroll down at all, the last TextView will be deleted, which makes me think it's a refresh problem, but I have no idea how to solve that.

Here's some of the code I'm using:

final TextView tv1 = new TextView(this);
tv1.setText("Test");

tv1.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        linearlayout1.removeView(tv1);

    }
});

I have also added this code in to try to solve the problem but it didn't change anything:

if (linearlayout1.getChildCount() == 1) {
    linearlayout1.removeAllViewsInLayout();
}
like image 604
NotACleverMan Avatar asked May 09 '11 08:05

NotACleverMan


People also ask

How to add a textview to a linearlayout dynamically in Android?

How to add a TextView to a LinearLayout dynamically in Android? This example demonstrates about How to add a TextView to a LinearLayout dynamically in Android Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

How do I remove all child views from a linearlayout?

Android remove all child views LinearLayout formLayout = (LinearLayout)findViewById(R.id.formLayout); formLayout.removeAllViews(); Labels: Android No comments:

How to add a view to a linear layout programmatically?

Add View to Linear Layout at a Specific Index Programmatically If you want to add a view at a specific index (or position) inside a linear layout you can do it by just writing below the line of code. linear_layout.addView (your_view, 2)

How to remove a Android view from layout using Activity Code?

How to remove a Android View from layout using Activity code Android remove view from parent View myView = findViewById(R.id.hiddenLayout); ViewGroup parent = (ViewGroup) myView.getParent(); parent.removeView(myView); Android remove all child views


1 Answers

This sounds more of a bug in Android, but one thing you could try is hiding your TextView before removal:

tv1.setVisibility(View.GONE)

Or alternatively you could add:

linearlayout1.invalidate()

after removal of the last item to trigger redrawing.

like image 185
harism Avatar answered Nov 14 '22 07:11

harism