Представления могут быть добавлены к ConstraintLayout
с использованием addView()
так же, как с LinearLayout
.Разница в том, что при ConstraintLayout
добавленные представления должны быть ограничены.Чтобы программно ограничить представление, используйте ConstraintSet
.
Этот класс позволяет программно определять набор ограничений, которые будут использоваться с ConstraintLayout.Это позволяет создавать и сохранять ограничения и применять их к существующему ConstraintLayout.
Вот краткий пример:
activity_main Определить два TextViews
.Отцентрируйте их горизонтально и расположите сверху.
<android.support.constraint.ConstraintLayout
android:id="@+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/topView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Top View"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/bottomView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Bottom View"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/topView" />
</android.support.constraint.ConstraintLayout>
Это то, что вы увидите, когда новый TextView
("Средний вид") будет добавлен в этот макет без установки ограничений.Обратите внимание, что новый вид по умолчанию имеет позицию (0,0).
![enter image description here](https://i.stack.imgur.com/nPXWJ.png)
Допустим, мы хотим, чтобы сгенерированный средний вид был расположен между верхомвид и вид снизу по центру в окне по горизонтали, например:
![enter image description here](https://i.stack.imgur.com/U0fO7.png)
Вот код, который даст этот результат:
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Define the new TextView and add it to the ConstraintLayout. Without constraints,
// this view will be positioned at (0,0).
TextView middleView = new TextView(this);
middleView.setId(View.generateViewId());
middleView.setText("Middle View");
middleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20.0f);
ConstraintLayout layout = findViewById(R.id.constraintLayout);
ConstraintLayout.LayoutParams lp =
new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT,
ConstraintLayout.LayoutParams.WRAP_CONTENT);
layout.addView(middleView, lp);
// Move the new view into place by applying constraints.
ConstraintSet set = new ConstraintSet();
// Get existing constraints. This will be the base for modification.
set.clone(layout);
int topMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
16, getResources().getDisplayMetrics());
// Set up the connections for the new view. Constrain its top to the bottom of the top view.
set.connect(middleView.getId(), ConstraintSet.TOP, R.id.topView, ConstraintSet.BOTTOM, topMargin);
// Constrain the top of the bottom view to the bottom of the new view. This will replace
// the constraint from the bottom view to the bottom of the top view.
set.connect(R.id.bottomView, ConstraintSet.TOP, middleView.getId(), ConstraintSet.BOTTOM, topMargin);
// Since views must be constrained vertically and horizontally, establish the horizontal
// constaints such that the new view is centered.
set.centerHorizontally(middleView.getId(),ConstraintSet.PARENT_ID);
// Finally, apply our good work to the layout.
set.applyTo(layout);
}