Android custom view group delegate addView

前端 未结 1 1611
既然无缘
既然无缘 2020-11-29 12:45

I want to implement custom ViewGroup in my case derived from FrameLayout but I want all child views added from xml to be added not directly into th

相关标签:
1条回答
  • 2020-11-29 13:15

    Views inflated from a layout - like your example TextView - are not added to their parent ViewGroup with addView(View child), which is why overriding just that method didn't work for you. You want to override addView(View child, int index, ViewGroup.LayoutParams params), which all of the other addView() overloads end up calling.

    In that method, check if the child being added is one of your two special FrameLayouts. If it is, let the super class handle the add. Otherwise, add the child to your container FrameLayout.

    public class CustomFrameLayout extends FrameLayout {
    
        private final FrameLayout topLayout;
        private final FrameLayout containerLayout;
    
        ...
    
        public CustomFrameLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
    
            LayoutInflater.from(context).inflate(R.layout.custom, this, true);
            topLayout = (FrameLayout) findViewById(R.id.frame_layout_top);
            containerLayout = (FrameLayout) findViewById(R.id.frame_layout_child_container);
        }
    
        @Override
        public void addView(View child, int index, ViewGroup.LayoutParams params) {
            final int id = child.getId();
            if (id == R.id.frame_layout_top || id == R.id.frame_layout_child_container) {
                super.addView(child, index, params);
            }
            else {
                containerLayout.addView(child, index, params);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题