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

android– 创建不需要在XML中设置layout_widthheight的自定义视图,第1张

概述是否可以创建一个自定义视图,以便可以引用它<components.layouts.CustomViewandroid:text="@string/sign_in_options"/>没有在xml中明确声明layout_width和layout_height,因为这已经在CustomView类中定义publicclassCustomViewextendsTextView{publicCusto

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

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

以上是内存溢出为你收集整理的android – 创建不需要在XML中设置layout_width / height的自定义视图全部内容,希望文章能够帮你解决android – 创建不需要在XML中设置layout_width / height的自定义视图所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1117396.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-29
下一篇2022-05-29

发表评论

登录后才能评论

评论列表(0条)

    保存