Java 如何以编程方式向 ConstraintLayout 添加视图和约束?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40275152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to programmatically add views and constraints to a ConstraintLayout?
提问by Kerooker
I'm having a problem to programmatically add views to a ConstraintLayout
, and set up all the constraints required for the layout to work.
我在以编程方式向 a 添加视图ConstraintLayout
并设置布局工作所需的所有约束时遇到问题。
What I have at the moment doesn't work:
我目前所拥有的不起作用:
ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.mainConstraint);
ConstraintSet set = new ConstraintSet();
set.clone(layout);
ImageView view = new ImageView(this);
layout.addView(view,0);
set.connect(view.getId(), ConstraintSet.TOP, layout.getId(), ConstraintSet.TOP, 60);
set.applyTo(layout);
The ImageView
doesn't even appear on the layout. When adding to a RelativeLayout
, it works like a charm.
该ImageView
甚至没有出现在布局。添加到 a 时RelativeLayout
,它就像一个魅力。
What can I do to create the constraints I need, so that my layout work again?
我可以做些什么来创建我需要的约束,以便我的布局再次工作?
采纳答案by rerashhh
I think you should clone the layout after adding your ImageView.
我认为您应该在添加 ImageView 后克隆布局。
ConstraintLayout parentLayout = (ConstraintLayout)findViewById(R.id.mainConstraint);
ConstraintSet set = new ConstraintSet();
ImageView childView = new ImageView(this);
// set view id, else getId() returns -1
childView.setId(View.generateViewId());
layout.addView(childView, 0);
set.clone(parentLayout);
// connect start and end point of views, in this case top of child to top of parent.
set.connect(childView.getId(), ConstraintSet.TOP, parentLayout.getId(), ConstraintSet.TOP, 60);
// ... similarly add other constraints
set.applyTo(parentLayout);