Android - do ViewGroup onDraw need to iterate through child view and call onDraw explicitly?

核能气质少年 提交于 2019-12-22 17:53:51

问题


I have spent the whole day debugging various ways to add custom ViewGroup into another custom ViewGroup and nearly went crazy because none of them works, and there is no official documentation or sample that shows how it can be done...

Basically, I have 2 custom ViewGroup:

  1. HorizontalDockView extends ViewGroup
  2. GameEntryView extends FrameLayout

HorizontalDockView overrides onDraw, onMeasure, etc and everything is called normally and works perfectly. However, when I create GameEntryView from inside HorizontalDockView's constructor and call addView(gameEntryView), the gameEntryView will never ever show regardless of the layoutParams, addView called from whatever thread, or however I call, load, and setContentView on the parent HorizontalDockView. If I list through the horizontalDockView.getChildAt(); all the gameEntryView objects are still there.

Hopeless, I try to debug through GameEntryView's onDraw, onMeasure, dispatchDraw methods and realized none of them actually get called! No.. not even once!

Do I need to iterate through all the child view in the parent (HorizontalDockView's) on* call and call the children's on* explicitly? I was just calling super.on*() on the parent.

I did call setWillNotDraw( false ); on both the parent and the child class.

How do I get the child to show up inside the parent's view? simple sample or existing small open source project is highly appreciated!

Thank you very much!


回答1:


Did you overwrite onLayout? When Android lays out your ViewGroup, your ViewGroup is responsible for laying out the children.

This code is from a custom ViewGroup that lays out all children on top of each other:

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

    int count = this.getChildCount();
    for (int i = 0; i < count; i++) {

        View child = this.getChildAt(i);
        child.layout(0, 0, child.getMeasuredWidth(), child.getMeasuredHeight());
    }
}

For completeness, the onMeasure override:

@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {

    int parentWidth  = MeasureSpec.getSize(widthMeasureSpec);
    int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
    this.setMeasuredDimension(parentWidth, parentHeight);

    int count = this.getChildCount();
    for (int i = 0; i < count; i++) {

        View child = this.getChildAt(i);
        this.measureChild(
            child,
            MeasureSpec.makeMeasureSpec(parentWidth, MeasureSpec.EXACTLY),
            MeasureSpec.makeMeasureSpec(parentHeight, MeasureSpec.EXACTLY));
    }
}


来源:https://stackoverflow.com/questions/17544209/android-do-viewgroup-ondraw-need-to-iterate-through-child-view-and-call-ondraw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!