在Android中,约束布局(ConstraintLayout)是一种灵活的布局管理器,可以通过设置约束条件来控制视图的位置和大小。程序化和预览是使用约束布局的两种不同方法。
ConstraintLayout constraintLayout = new ConstraintLayout(context);
constraintLayout.setLayoutParams(new ConstraintLayout.LayoutParams(
ConstraintLayout.LayoutParams.MATCH_PARENT,
ConstraintLayout.LayoutParams.MATCH_PARENT));
TextView textView = new TextView(context);
textView.setText("Hello, ConstraintLayout!");
// 设置文本视图的约束条件
ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(
ConstraintLayout.LayoutParams.WRAP_CONTENT,
ConstraintLayout.LayoutParams.WRAP_CONTENT);
layoutParams.startToStart = ConstraintLayout.LayoutParams.PARENT_ID;
layoutParams.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID;
layoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
layoutParams.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
textView.setLayoutParams(layoutParams);
// 将文本视图添加到约束布局
constraintLayout.addView(textView);
// 将约束布局添加到父容器
parentLayout.addView(constraintLayout);
以上是使用程序化和预览方法创建和设置约束布局的解决方案。具体选择哪种方法取决于你的需求和个人喜好。