ViewGroup onLayout问题

发布于 2024-11-26 16:56:59 字数 1013 浏览 2 评论 0原文

我的自定义 ViewGroup 有问题。我将 3 个子项排成一行,并使用 Scroller 滚动到中间的子项。根据用户的触摸输入,我更改应显示的子项并请求新的布局。然后我按照新的顺序排列孩子们。但是,当一个子项已在先前的布局中显示时,运行这些子项会彼此叠置。我检查了子级是否以正确的方式获得布局,我认为旧布局没有被删除,新的子级只是绘制在旧布局之上。有没有办法确保旧布局被清除或其他什么?

这是我的代码:

@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);
    ...
}

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);
    ...
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

阳光下慵懒的猫 2024-12-03 16:56:59

尝试在 onLayout() 末尾调用 invalidate()

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文