大家晚安。
我正在尝试以编程方式将按钮添加到ConstraintLayout
并将ConstraintSet
设置为此类按钮。
当我尝试从布局中关闭constraintSet时出现问题,因为我添加的按钮没有ID。
Button button = new Button(this);
ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(250, ConstraintLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(15,15,15,15);
button.setLayoutParams(params);
button.setText(returnObject.getFunction());
button.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
button.setTextColor(R.drawable.custom_button_color);
button.setBackgroundResource(R.drawable.custom_button);
ConstraintLayout container = findViewById(R.id.highLevelContainer);
container.addView(button);
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(container); // Here I get the error
constraintSet.connect(button.getId(), ConstraintSet.END , container.getId(), ConstraintSet.END,0);
constraintSet.connect(button.getId(), ConstraintSet.START, container.getId(),ConstraintSet.START,0);
constraintSet.connect(button.getId(), ConstraintSet.TOP, container.getId(), ConstraintSet.TOP);
constraintSet.applyTo(container);
这是在控制台上生成的错误:
java.lang.RuntimeException: All children of ConstraintLayout must have ids to use ConstraintSet
at android.support.constraint.ConstraintSet.clone
我希望避免在循环中为按钮分配一个随机数作为ID。 知道如何解决这个问题吗?