How to remove child of horizontalview in android

2019-08-20 07:59发布

问题:

I faced not delete child inside the horizontalview. if already have child of horizontalview then delete or remove and if not child then addview. please see code, what i did. but why this not working.

Result: it append previous view in horizontall layout.

first time:
Horizontalview
1 4 7

second time
Horizontalview
1 4 7 6 0 7 8

but i want

second time
Horizontalview
 6 0 7 8

third time
Horizontalview
 2 9 5

my code

   if(horizontalScrollview.getChildCount()>0){
        horizontalScrollview.removeAllViews();
        horizontalScrollview.addView(dataLayout);
    }else {
        horizontalScrollview.addView(dataLayout);
    }

回答1:

HorizantalScrollView contains only one child view , that child may add or remove child views, try this:

if (horizontalScrollview.getChildCount() > 0) {
            horizontalScrollview.removeAllViews();
            horizontalScrollview.addView(dataLayout);
        } else {
            horizontalScrollview.addView(dataLayout);
        }

to

    ViewGroup parentLayout = (ViewGroup) horizontalScrollview.getChildAt(0);

    if (parentLayout.getChildCount() > 0) {
        for (int i = 0; i < parentLayout.getChildCount(); i++) {
            parentLayout.removeView(parentLayout.getChildAt(i));
        }
    } else {
        parentLayout.addView(dataLayout);
    }