Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating custom view that doesn't require layout_width/height set in XML

Tags:

android

xml

Is it possible to create a custom view such that it could be refer to by

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

without explicitly stating the layout_width and layout_height in xml since this is already defined in the CustomView class as such

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

does anyone know if there's a way to do it?

like image 915
DarkPhoton Avatar asked Nov 07 '22 20:11

DarkPhoton


1 Answers

try this:

@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    measureChild(yourChild,parentWidthMeasureSpec,parentHeightMeasureSpec);
}
like image 134
naser khsoravi Avatar answered Nov 14 '22 23:11

naser khsoravi