ViewGroup onLayout Problem

2019-07-19 00:10发布

问题:

I have a problem with my custom ViewGroup. I layout 3 of the children in a row and use a Scroller to scroll to the middle child. Based on the touch input of the user I change the children that should be displayed and request a new layout. Then I layout the children in a new order. But when one child has been displayed in a previous layout run the children lie on top of each other. I checked that the children get layout in the right way and I think the old layout is not deleted and the new children get just drawn on top of the old layout. Is there a way to ensure that the old layout gets cleared or something?

Here is my code:

@Override
public boolean onTouchEvent(MotionEvent event) {
    ...
    case MotionEvent.ACTION_UP:
        if(old != current)
            this.requestLayout();
        else
            this.scrollTo(getWidth(), 0);
    ...
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    // show current-1, current, current+1
    int count = 0;
    for(int i = 1; i >= -1; i--) {
        // determine index of child
        // the mod does a modulo
        int index = mod(current-i, getChildCount());
        // position in row from left to right
        this.getChildAt(index).layout(count*this.getWidth(), 0, (count+1)*this.getWidth(), height);
        count++;
    }
    // scroll to middle view
    this.scrollTo(getWidth(), 0);
    ...
}

回答1:

Try to call invalidate() at the end of onLayout().