[英]How to dynamically add a linear layout (as a child) to a constraint layout (parent)?
I defined a method to create a linear layout and to add it to parent layout. 我定义了一种方法来创建线性布局并将其添加到父布局。 But it didn't work.
但它没有用。 I think I made mistake(s).
我想我犯了错误。
public void methodName() {
LinearLayout linearLayout = new LinearLayout(MainActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
linearLayout.setLayoutParams(params);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setBackgroundColor(Color.RED);
ConstraintLayout main = (ConstraintLayout) findViewById(R.id.mainLayout);
main.addView(linearLayout);
}
To add views to a ConstraintLayout you have to add the constraints using a ConstraintSet. 要向ConstraintLayout添加视图,必须使用ConstraintSet添加约束。
While Adding dynamic views to constraint layout, it is a bit different from other layouts. 在为约束布局添加动态视图时,它与其他布局略有不同。 You need to specify the constraints as well like this below:-
您需要指定约束,如下所示: -
ConstraintLayout main = (ConstraintLayout) findViewById(R.id.mainLayout);
ConstraintSet set = new ConstraintSet();
LinearLayout linearLayout = new LinearLayout(MainActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
linearLayout.setLayoutParams(params);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setBackgroundColor(Color.RED);
main.addView(linearLayout,0);
set.clone(main);
set.connect(linearLayout.getId(), ConstraintSet.TOP, main.getId(), ConstraintSet.TOP, 60);
set.applyTo(main);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.