我想在ConstraintLayout中添加2个按钮。 我当前的代码如下:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.activity_main);
ConstraintSet set = new ConstraintSet();
set.clone(layout);
//Button 1:
Button button = new Button(this);
button.setText("Hello");
layout.addView(button);
set.connect(button.getId(), ConstraintSet.LEFT, layout.getId(), ConstraintSet.LEFT, 0);
set.connect(button.getId(), ConstraintSet.RIGHT, layout.getId(), ConstraintSet.RIGHT, 0);
set.connect(button.getId(), ConstraintSet.BOTTOM, layout.getId(), ConstraintSet.BOTTOM, 0);
set.constrainWidth(button.getId(), ConstraintSet.MATCH_CONSTRAINT);
set.constrainHeight(button.getId(), 200);
set.applyTo(layout);
//Button 2:
Button newButton = new Button(this);
newButton.setText("Yeeey");
layout.addView(newButton);
set.connect(newButton.getId(), ConstraintSet.BOTTOM, button.getId(), ConstraintSet.TOP, 0);
set.connect(newButton.getId(), ConstraintSet.LEFT, button.getId(), ConstraintSet.LEFT, 0);
set.connect(newButton.getId(), ConstraintSet.RIGHT, button.getId(), ConstraintSet.RIGHT, 0);
set.constrainHeight(newButton.getId(), 200);
set.applyTo(layout);
}
但是我只看到了一个可见的按钮(另一个可能隐藏在这个按钮后面),而且它在屏幕左上角。应该有两个按钮,位于屏幕底部,彼此链接。
我做错了什么?
期望结果:
View.generateViewId()
方法代替使用整型常量作为参数。 - user8389458