Положение переключателя макета ограничения по отношению к другому виду - PullRequest
0 голосов
/ 16 ноября 2018

В этом макете кнопка изначально находится на правой стороне textview.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/frameLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.switchside.SwitchSideFragment">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:text="Hello"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/button"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Что может быть проще, во время выполнения поместить кнопку с левой стороны textview, при этом ее левая сторона соединена с левой стороной родительского элемента?

1 Ответ

0 голосов
/ 16 ноября 2018

Если я правильно понял, то, чего вы хотите добиться, это переместить кнопку из одной стороны в другую в текстовом представлении. Конечно, вы можете сделать это программно, просто изменив ограничения, которые вы применили к кнопке. Это, безусловно, будет работать, но ремонтопригодность этого решения низкая по сравнению с другими решениями.

Я предлагаю использовать ConstraintSets. ConstraintSets - это набор правил, ограничений. Вы уже определили набор ограничений в этом файле макета. Вы можете продублировать этот точный файл макета, изменив его имя и применив другие ограничения: у вас будет новый набор ограничений. Обратите внимание, что вам придется использовать те же идентификаторы, чтобы заставить ConstraintSets работать. Это обязательно.

После создания второго набора вы можете просто переключиться с одного на другой, применив выбранный набор к корневому ConstraintLayout. Пожалуйста, ознакомьтесь с официальной документацией для полного примера: https://developer.android.com/reference/android/support/constraint/ConstraintSet

EDIT: Я добавлю пример. Начнем с первого макета XML, назовем его R.layout.first, создадим второй, назовем его R.layout.second.

Чтобы программно переключиться с первого на второе, вам нужно сделать что-то похожее на это:

ConstraintSet firstCS = new ConstraintSet(); //this will reference the first set
ConstraintSet secondCS = new ConstraintSet(); // this will reference the second set
ConstraintLayout constraintLayout = findViewByID(R.id.frameLayout); //this will reference the root constraint layout in your layout XML

firstCS.clone(constraintLayout); // you will get the first set directly from the root layout
secondCS.clone(getContext(), R.layout.second); //and you will clone the second set from your layout XML
secondCS.applyTo(constraintLayout); // this will apply the second set 
...