gpt4 book ai didi

android - 创建不需要在 XML 中设置 layout_width/height 的自定义 View

转载 作者:太空宇宙 更新时间:2023-11-03 10:35:59 28 4
gpt4 key购买 nike

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

<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 的自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44859904/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com