在Android应用程序中,我尝试以编程方式将自定义ConstraintLayout
视图添加到垂直方向LinearLayout
。
我将LayoutParams
设置为MATCH_PARENT
的宽度,将WRAP_CONTENT
设置为ConstraintLayout
的高度。但是,当我运行应用程序时,ConstraintView
全部被压缩,内容重叠。以下是一些相关的片段和我的应用程序的屏幕截图。我该如何纠正这个问题?
public class ItemView extends ConstraintLayout {
LinearLayout linearButtons;
LinearLayout linearText;
public ItemView(Context context, String name, String price, ArrayList<String> guests,
ArrayList<String> checked, int id) {
...
addView(linearText);
addView(linearButtons);
set.clone(this);
set.connect(linearText.getId(), ConstraintSet.LEFT, this.getId(),
ConstraintSet.LEFT, 8);
set.connect(linearText.getId(), ConstraintSet.TOP, this.getId(),
ConstraintSet.TOP, 8);
set.connect(linearButtons.getId(), ConstraintSet.RIGHT, this.getId(),
ConstraintSet.RIGHT, 8);
set.connect(linearButtons.getId(), ConstraintSet.TOP, this.getId(),
ConstraintSet.TOP, 8);
}
别处:
for (Item it:r.getItems()) {
ItemView itemView = new ItemView(this, it.getName(), nf.format(it.getPrice()), dinerlist, it.getGuests(), i);
ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.MATCH_PARENT);
itemView.setLayoutParams(params);
vg.addV[enter image description here][1]iew(itemView);
Log.d("ItemView Children: ", itemView.getWidth()+" "+itemView.getHeight());
答案 0 :(得分:7)
在xml中的ConstraintLayout中,如果需要“MATCH_PARENT”宽度,则必须将宽度设置为0dp,然后将layout_constraintWidth_default属性设置为“spread”
以编程方式,您也可以这样做:
a)设置0 dp的宽度和高度
b)设置defaultWidth和defaultHeight约束
//add the view with 0dp width and height
val layoutParams = ConstraintLayout.LayoutParams(0, 0)
val view = View(context)
view.layoutParams = layoutParams
view.id = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) View.generateViewId() else 1138
parent.addView(view)
//apply the default width and height constraints in code
val constraints = ConstraintSet()
constraints.clone(parent)
constraints.constrainDefaultHeight(view.id, ConstraintSet.MATCH_CONSTRAINT_SPREAD)
constraints.constrainDefaultWidth(view.id, ConstraintSet.MATCH_CONSTRAINT_SPREAD)
constraints.applyTo(parent)
如果您需要Java:
//add the view with 0dp width and height
ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(0, 0);
View view = View(context);
view.setLayoutParams(layoutParams);
view.setId(1138);
parent.addView(view);
//apply the default width and height constraints in code
ConstraintSet constraints = new ConstraintSet();
constraints.clone(parent);
constraints.constrainDefaultHeight(view.getId(), ConstraintSet.MATCH_CONSTRAINT_SPREAD);
constraints.constrainDefaultWidth(view.getId(), ConstraintSet.MATCH_CONSTRAINT_SPREAD);
constraints.applyTo(parent);