在代码中创建 Android ConstraintLayout 和 Guidelines
Creating Android ConstraintLayout and Guidelines in code
如何以编程方式创建 ConstraintLayouts 和 Guidelines?我已经尝试使用下面的代码创建一个简单的布局,使用指南将视图锚定到屏幕中间,但它在屏幕左侧呈现红色 'v' 视图(参见 screenshot)
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);
}
}
您使用的 ConstraintLayout
是哪个版本?用 beta 3 尝试你的例子,我得到了正确的行为:
编辑 -- 我错了,beta 4 已经修复了这个问题。
此外,要使用 ConstraintLayout 以编程方式创建布局参数,您应该在 ConstraintLayout.LayoutParams 上调用 validate() 函数,然后再将其设置到视图。
这是一个错误,现已在 beta4 中修复。请注意,您必须在代码中设置 ConstraintLayout.LayoutParams 后调用 lp.validate() 。更多详情请见 https://code.google.com/p/android/issues/detail?id=227039。
如何以编程方式创建 ConstraintLayouts 和 Guidelines?我已经尝试使用下面的代码创建一个简单的布局,使用指南将视图锚定到屏幕中间,但它在屏幕左侧呈现红色 'v' 视图(参见 screenshot)
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);
}
}
您使用的 ConstraintLayout
是哪个版本?用 beta 3 尝试你的例子,我得到了正确的行为:
编辑 -- 我错了,beta 4 已经修复了这个问题。
此外,要使用 ConstraintLayout 以编程方式创建布局参数,您应该在 ConstraintLayout.LayoutParams 上调用 validate() 函数,然后再将其设置到视图。
这是一个错误,现已在 beta4 中修复。请注意,您必须在代码中设置 ConstraintLayout.LayoutParams 后调用 lp.validate() 。更多详情请见 https://code.google.com/p/android/issues/detail?id=227039。