您將需要使用應用於ImageView
的ConstraintSet
來居中。 ConstraintSet
的文檔可以在here找到。
該類允許您以編程方式定義與ConstraintLayout一起使用的一組約束。它允許您創建和保存約束,並將它們應用於現有的ConstraintLayout。 ConstraintsSet可以以各種方式創建...
也許這裏最棘手的事情是視圖如何居中。對中技術的一個很好的描述是here。
對於你的榜樣,下面的代碼就足夠了:
// Get existing constraints into a ConstraintSet
ConstraintSet constraints = new ConstraintSet();
constraints.clone(layout);
// Define our ImageView and add it to layout
ImageView imageView = new ImageView(this);
imageView.setId(View.generateViewId());
imageView.setImageResource(R.drawable.redlight);
layout.addView(imageView);
// Now constrain the ImageView so it is centered on the screen.
// There is also a "center" method that can be used here.
constraints.constrainWidth(imageView.getId(), ConstraintSet.WRAP_CONTENT);
constraints.constrainHeight(imageView.getId(), ConstraintSet.WRAP_CONTENT);
constraints.center(imageView.getId(), ConstraintSet.PARENT_ID, ConstraintSet.LEFT,
0, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT, 0, 0.5f);
constraints.center(imageView.getId(), ConstraintSet.PARENT_ID, ConstraintSet.TOP,
0, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, 0, 0.5f);
constraints.applyTo(layout);