Android ViewGroup: what should I do in the onLayout() override?

后端 未结 2 479
暖寄归人
暖寄归人 2020-12-24 13:24

When extending an Android ViewGroup class, what is the purpose of the onLayout() override? I\'m making a custom control in Android but for some reason the cont

相关标签:
2条回答
  • 2020-12-24 13:35

    Actually it helps in positioning children of a view group. following code may help

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    MarginLayoutParams layoutParams = (MarginLayoutParams) icon.getLayoutParams();
    
    // Figure out the x-coordinate and y-coordinate of the icon.
    int x = getPaddingLeft() + layoutParams.leftMargin;
    int y = getPaddingTop() + layoutParams.topMargin;
    
    // Layout the icon.
    icon.layout(x, y, x + icon.getMeasuredWidth(), y + icon.getMeasuredHeight());
    
    // Calculate the x-coordinate of the title: icon's right coordinate +
    // the icon's right margin.
    x += icon.getMeasuredWidth() + layoutParams.rightMargin;
    
    // Add in the title's left margin.
    layoutParams = (MarginLayoutParams) titleView.getLayoutParams();
    x += layoutParams.leftMargin;
    
    // Calculate the y-coordinate of the title: this ViewGroup's top padding +
    // the title's top margin
    y = getPaddingTop() + layoutParams.topMargin;
    
    // Layout the title.
    titleView.layout(x, y, x + titleView.getMeasuredWidth(), y + titleView.getMeasuredHeight());
    
    // The subtitle has the same x-coordinate as the title. So no more calculating there.
    
    // Calculate the y-coordinate of the subtitle: the title's bottom coordinate +
    // the title's bottom margin.
    

    ...

    you can find more detail about custom views here custom views

    0 讨论(0)
  • 2020-12-24 13:51

    In onLayout you need to call layout method on each child of this ViewGroup and provide desired position (relatively to parent) for them. You can check source code of FrameLayout (one of the simpliest subclasses of ViewGroup) to find out how it works.

    Although, if you don't need any "special" layouting, you have other options:

    • Extend some another subclass of ViewGroup instead (FrameLayout for example)
    • Use LayoutInflater if you just need your control to look exactly as in XML (which, I think, is exactly your case)
    0 讨论(0)
提交回复
热议问题