我尝试用Java动态创建一个按钮,并添加一些约束来将它定位在我的constrainLayout的中心。所以我写了这段代码:
import android.app.Activity;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.constraint.ConstraintSet;
import android.widget.Button;
public class SelectGameActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_game);
ConstraintSet constraintSet = new ConstraintSet();
ConstraintLayout constraintLayout = findViewById(R.id.constraintLayout);
constraintSet.clone(constraintLayout);
Button button = new Button(this);
button.setText("test");
button.setId(213);
constraintLayout.addView(button);
constraintSet.connect(button.getId(), ConstraintSet.LEFT, R.id.constraintLayout, ConstraintSet.LEFT);
constraintSet.connect(button.getId(), ConstraintSet.RIGHT, R.id.constraintLayout, ConstraintSet.RIGHT);
constraintSet.connect(button.getId(), ConstraintSet.TOP, R.id.constraintLayout, ConstraintSet.TOP);
constraintSet.connect(button.getId(), ConstraintSet.BOTTOM, R.id.constraintLayout, ConstraintSet.BOTTOM);
constraintSet.applyTo(constraintLayout);
}
}
它可以工作,但按钮会填满所有屏幕:
我认为这是因为我的按钮没有任何特定的高度和宽度。我尝试了几个代码来给它一个大小但没有效果。有人可以给我一些提示来正确调整我的按钮大小吗?
非常感谢!
查尔斯
答案 0 :(得分:1)
尝试将按钮的尺寸设置为WRAP_CONTENT,如下所示:
constraintSet.constrainHeight(button.getId(), ConstraintSet.WRAP_CONTENT);
constraintSet.constrainWidth(button.getId(), ConstraintSet.WRAP_CONTENT);