简体   繁体   中英

View with visibility state GONE taking up space on screen

I am experiencing a problem where views with a visibility state of GONE are (undesirably) taking up space on the screen. This problem occurs always on API level <= 7 devices, but only recently on 8+ devices (after I utilized AsyncTasks to populate some fields, as per Show a progress bar when an Activity is loading )

A bit of context: I created a custom view extending LinearLayout that contains a "title" button and (user defined; in some cases, it's a few TextViews, in others it's TableLayouts) "contents". The purpose of this view is to toggle view of the contents onClick of the title button (I don't believe there is a built-in widget for this.. I may be wrong).

In onLayout() I explicitly set the visibility state of all child views except the title to GONE, the first time it is to be drawn:

protected void onLayout(boolean changed, int l, int t, int r, int b) {
    if(initialDraw) {
        setContentsVisible(false);
        initialDraw = false;
    }
    super.onLayout(changed, l, t, r, b);
}

public void setContentsVisible(boolean visible) {
    for(int i = 0; i < getChildCount(); i++) {
        View child = getChildAt(i);

        if(child != mTitle) {
            child.setVisibility(visible ? VISIBLE : GONE);
        }
    }
}

将代码从onLayout()移动到onMeasure()可以解决问题。

Ok. I don't understand how it draws anything in your situation at all. But I think you should call super.onLayout() after your check. Like this:

protected void onLayout(boolean changed, int l, int t, int r, int b) {
    if(initialDraw) {
        setContentsVisible(false);
        initialDraw = false;
    }
    super.onLayout(l,t,r,b);
}

LinearLayout decides how to layout it's children (vertically, or horizontally) in onLayout(), which you didn't call. More to it, after choosing, it actually starts calculating how to layout each child, and if the child's visibility is GONE, it skips it (means the child won't take any space). I think in your case, no children at all would be layed out and shown, but I might be wrong somewhere.

I suspect you are making your life unnecessarily difficult. Make the extensible part of your view (the non-title bit with the few TextViews or TableLayouts) belong to a single container View - a FrameLayout seems a likely choice - and just call setVisibility() on that.

No need for looping, and you definitely don't want to do it from onLayout()... just do it from your title's onClick() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM