以编程方式使用 ConstraintSet 将 Button 添加到 ConstrainLayout

问题描述 投票:0回答:1

大家好。

我正在尝试以编程方式将按钮添加到

ConstraintLayout
并将
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,因为它是在循环中创建的。 知道如何解决这个问题吗?

android android-button android-constraintlayout constraintset
1个回答
0
投票

您只需将 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.setId(View.generateViewId());   <----HERE

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); 
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);
© www.soinside.com 2019 - 2024. All rights reserved.