добавить динамические дочерние представления по вертикали в ConstraintLayout - PullRequest
0 голосов
/ 25 сентября 2018

Android ViewGroup имеет следующие методы для добавления (дочерних) просмотров:

enter image description here

Я знаю, что мы можем легко определить горизонтальную / вертикальную ориентацию дляLinearLayout в xml / программно и добавить дочерние представления, например.

enter image description here

Аналогично RelativeLayout, мы можем использовать метод ViewGroup '* addView и RelativeLayout.LayoutParams:

enter image description here

Я также знаю, что мы можем использовать LinearLayout в качестве ребенка внутри ConstraintLayout и играть с ним.

Есть ли какие-либо твердые и рекомендуемыеспособ динамического добавления дочерних представлений в ConstraintLayout?

ОБНОВЛЕНИЕ : Позвольте мне привести не такой простой пример, которого я хочу достичь.

Предположим, у вас естьa View 1, View 2 и View 3.Все V1, V2 и V3 выровнены вертикально один под другим и представляют собой сложные виды, состоящие из нескольких TextView с и ImageView с.Исходя из действий пользователя и того, какой сервер отправляет информацию, мне нужно добавить несколько V1 и V2 (может быть 1 пара V1-V2 и 3 пары V1-V2) между исходными V2 и V3.Если я использую ConstraintLayout, было бы лучше, если бы я добавил несколько ограничений программно, когда я могу легко использовать LinearLayout с вертикальной ориентацией?

Теперь, с точки зрения эффективности, производительности и менее красивого кода,ConstraintLayout лучше всего подходит для этого требования по сравнению с Linear Layout?

1 Ответ

0 голосов
/ 25 сентября 2018

Представления могут быть добавлены к 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

Допустим, мы хотим, чтобы сгенерированный средний вид был расположен между верхомвид и вид снизу по центру в окне по горизонтали, например:

enter image description here

Вот код, который даст этот результат:

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);
}
...