gpt4 book ai didi

android - 使用 ConstraintSet 以编程方式向 View 添加约束不会在 Android 中给出预期结果?

转载 作者:行者123 更新时间:2023-11-29 23:20:36 25 4
gpt4 key购买 nike

我有一个自定义的 ConstraintLayout,里面有一个 TextView。我正在以编程方式WITHOUT XML来做所有事情,代码如下:

public class CustomView extends ConstraintLayout {
private TextView textView;

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

textView = new TextView(context);
textView.setId(View.generateViewId());
textView.setText("...");

// Adding border to the view in order to visualize the frame
GradientDrawable border = new GradientDrawable();
border.setColor(Color.TRANSPARENT);
border.setStroke(1, Color.BLACK);
textView.setBackground(border);
addView(textView);

// Apply constraints to textView. Left = right = top = bottom = 120

ConstraintSet set = new ConstraintSet();
set.clone(this);
set.connect(textView.getId(), ConstraintSet.LEFT, ConstraintSet.PARENT_ID, ConstraintSet.LEFT, 120);
set.connect(textView.getId(), ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP, 120);
set.connect(textView.getId(), ConstraintSet.RIGHT, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, 120);
set.connect(textView.getId(), ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, 120);
set.applyTo(this);
}
}

当我运行上面的代码时,我得到了一些错误的结果:

  1. 如果 textView 中的文本很短:

enter image description here

  1. 如果textView中的文本很长:

enter image description here

最佳答案

如果我理解更正您的错误结果 - 您没有看到边距?我认为这是因为您的 TextView 的默认 layout_width layout_height - wrap_content。默认值必须是 0dp。像这样尝试:

LayoutParams lp = new LayoutParams(0, 0);
textView.setLayoutParams(lp);

关于android - 使用 ConstraintSet 以编程方式向 View 添加约束不会在 Android 中给出预期结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54384742/

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