如何以编程方式创建 ConstraintLayouts 和 Guidelines?我尝试使用以下代码创建一个简单的布局,该布局使用指南将视图锚定到屏幕中间,但它在屏幕左侧呈现红色“v”视图(见截图)
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ConstraintLayout cl = new ConstraintLayout(this);
cl.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
setContentView(cl);
Guideline gl = new Guideline(this);
ConstraintLayout.LayoutParams gllp = new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 500);
gllp.guidePercent = 0.5f;
gllp.orientation = LinearLayout.VERTICAL;
gl.setLayoutParams(gllp);
gl.setId(View.generateViewId());
cl.addView(gl);
View v = new View(this);
v.setId(View.generateViewId());
v.setBackgroundColor(0xFFFF0000);
ConstraintLayout.LayoutParams lp = new ConstraintLayout.LayoutParams(50, 500);
lp.rightToRight = gl.getId();
v.setLayoutParams(lp);
cl.addView(v);
}
}