Android custom component doesn't display its children

前端 未结 1 1167
情话喂你
情话喂你 2020-12-22 06:21

Hi guys I want to create a FieldSet component in Android. (similar to html) so something like that. So I want my custom component to have children

相关标签:
1条回答
  • 2020-12-22 06:37

    When extending ViewGroup directly, you need to handle measuring and laying out the child Views yourself, or they never get sized or positioned correctly. Oftentimes, it's simpler to extend a ViewGroup subclass that already handles that stuff. In this case, you might as well extend RelativeLayout, since that's what's actually holding the internal Views, and the ViewGroup wrapping it is rather unnecessary.

    The parent RelativeLayout in the internal layout XML is then redundant, and can be replaced with <merge> tags, which will cause the child Views to be added directly to your RelativeLayout subclass when inflated.

    <merge xmlns:android="http://schemas.android.com/apk/res/android">
    
        <RelativeLayout
            android:id="@+id/field_set_content"
            ... />
    
        <TextView
            android:id="@+id/field_set_label"
            ... />
    
    </merge>
    

    We can further simplify things by setting up the internal structure in the constructor(s), and putting the child Views in the right place as they're added, rather than juggling all of that around in onFinishInflate(). For example:

    public class FieldSet extends RelativeLayout {
    
        final ViewGroup vg;
    
        public FieldSet(Context context, AttributeSet attrs) {
            super(context, attrs);
    
            LayoutInflater.from(context).inflate(R.layout.field_set, this, true);
            vg = (ViewGroup) findViewById(R.id.field_set_content);
        }
    
        @Override
        public void addView(View child, int index, ViewGroup.LayoutParams params) {
            final int id = child.getId();
            if (id == R.id.field_set_content || id == R.id.field_set_label) {
                super.addView(child, index, params);
            }
            else {
                vg.addView(child, index, params);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题