1

I have a Custom ViewGroup and I override onLayout method to layout its children. Every time onLayout called just some of children need to be layout. The problem is when I call requestLayout() the children that i don't layout them are shown from last call.

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {

    .
    .
    .
    // calculate a and b parameter

    for (int i = a; i < b ; i++) {
        getChildAt(i).layout(l, t ,r ,b );
    }


}

The question is How hide a child from layout or clear ViewGroup and relayout children ? or any other solution ...

A. Nateghi
  • 11
  • 2
  • Besides keeping a SparseArray of what should be visible and what not, there's no other "clean" way to do this. But why would you lay-out only some children? For speed? Think again and notice that leaving some of the children out might have some undesirable effects. – ssuukk Sep 25 '15 at 12:58
  • It's like a listView so some children are out of screen. Also position of each child need math calculation. I lay out children manually and animate with a Runnable and call requestLayout (). If you can't understand what I need I can post all of the source. – A. Nateghi Sep 27 '15 at 11:31

1 Answers1

0

In case anyone still has this problem, my solution was to address ALL the child views in onLayout:

  • set visibility = View.VISIBLE and call layout on the ones I want to show
  • set visibility = View.GONE for the ones I want to hide (and don't call layout on them). You can't just not lay them out if they are already there.

Alternatively, others have suggested you can override onDraw and clear the canvas:

 override fun onDraw(canvas: Canvas?) {

        // clear if new layout to get rid of unused views:
        if(clearCanvas) {  
            canvas?.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
            clearCanvas = false;
        }

        super.onDraw(canvas)
    }

Set clearCanvas = true in onLayout, when you know things have changed, and call invalidate().

However, I was not able to get it to call my onDraw() function ever! So, while this seems cleaner, there's something I'm still missing...

alr3000
  • 83
  • 11