android – 创建不需要在XML中设置layout_width / height的自定义视图

是否可以创建一个自定义视图,以便可以引用它

<components.layouts.CustomView
    android:text="@string/sign_in_options" />

没有在xml中明确声明layout_width和layout_height,因为这已经在CustomView类中定义

public class CustomView extends TextView {

    public CustomView(Context context) {
        super(context);
        setup();
    }

    public CustomView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setup();
    }

    public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setup();
    }

    public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        setup();
    }

    private void setup() {
        setLayoutParams(new ConstraintLayout.LayoutParams(
                ConstraintLayout.LayoutParams.MATCH_PARENT,
                ConstraintLayout.LayoutParams.WRAP_CONTENT));

        setBackgroundColor(getResources().getColor(R.color.background));
        setTextAlignment(TextView.TEXT_ALIGNMENT_CENTER);
        setAllCaps(true);

        int i = (int)getResources().getDimension(R.dimen.inner_space);
        setPadding(i, i, i, i);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        ViewGroup.MarginLayoutParams margins = ViewGroup.MarginLayoutParams.class.cast(getLayoutParams());
        int h = (int)getResources().getDimension(R.dimen.horizontal_space);
        margins.setMargins(0, h, 0, h);
        setLayoutParams(margins);
    }
}

有谁知道有没有办法做到这一点?

最佳答案 试试这个:

@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    measureChild(yourChild,parentWidthMeasureSpec,parentHeightMeasureSpec);
}
点赞