Комбинация макетов ограничений SPREAD и PACKED - PullRequest
6 голосов
/ 12 февраля 2020

Я хочу создать следующее ConstraintLayout:

enter image description here

Другими словами, я хочу создать цепочку, в которой все элементы распространение и только второй и третий упакованы . Я могу сделать это, удалив третий элемент из цепочки и применив к нему следующий код:

app:layout_constraintTop_toBottomOf="@+id/second_element"

он работает как положено.

НО

В случае небольшого устройства, в котором эта цепь сдвинута вместе, третий элемент будет выше четвертого элемента . Вот так:

enter image description here

В этом случае мне нужно, чтобы оно было равномерно расположено:

enter image description here

Спасибо за любую помощь.

Ответы [ 4 ]

0 голосов
/ 23 февраля 2020

Я решил это, извлекая 2-й и 3-й элементы в отдельный макет:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout ... >

   <TextView
      android:id="@+id/second"
      app:layout_constraintTop_toTopOf="parent"
      ...
      />

  <TextView
      android:id="@+id/third"
      app:layout_constraintTop_toBottomOf="@id/second"
      ...
      />

</androidx.constraintlayout.widget.ConstraintLayout>

И включив его в основной макет. Этот включенный макет заменит 2-й и 3-й элемент. Добавляя его в вертикальную цепочку, все работает как положено.

0 голосов
/ 12 февраля 2020

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

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

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val constraintLayout = findViewById<ConstraintLayout>(R.id.mainLayout)
        constraintLayout.doOnLayout {
            val tv3 = findViewById<View>(R.id.textView3)
            val tv4 = findViewById<View>(R.id.textView4)
            if (tv4.top < tv3.bottom) {
                val constraintSet = ConstraintSet()
                constraintSet.clone(constraintLayout)
                constraintSet.createVerticalChain(
                    ConstraintSet.PARENT_ID,
                    ConstraintSet.TOP,
                    ConstraintSet.PARENT_ID,
                    ConstraintSet.BOTTOM,
                    intArrayOf(
                        R.id.textView1,
                        R.id.textView2,
                        R.id.textView3,
                        R.id.textView4,
                        R.id.textView5
                    ),
                    null,
                    ConstraintSet.CHAIN_SPREAD
                )
                constraintSet.applyTo(constraintLayout)
            }
        }
    }
}
0 голосов
/ 13 февраля 2020

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

activity_man. xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Activity_Camera">

    <Button
        android:id="@+id/first_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="#03A9F4"
        android:padding="10dp"
        android:text="1"
        android:textAlignment="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.20" />

    <Button
        android:id="@+id/secon_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:backgroundTint="#F44336"
        android:padding="10dp"
        android:text="2"
        android:textAlignment="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.501"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/first_id"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/third_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="#FF5722"
        android:padding="10dp"
        android:text="3"
        android:textAlignment="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.50"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/secon_id"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/four_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:backgroundTint="#8BC34A"
        android:padding="10dp"
        android:text="4"
        android:textAlignment="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.50"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/third_id"
        app:layout_constraintVertical_bias="0.0" />

    <Button
        android:id="@+id/five_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:backgroundTint="#673AB7"
        android:padding="10dp"
        android:text="5"
        android:textAlignment="center"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.50"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/four_id"
        app:layout_constraintVertical_bias="0.0" />

</androidx.constraintlayout.widget.ConstraintLayout>
0 голосов
/ 12 февраля 2020

Попробуйте,

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/buttonOne"
        android:layout_width="wrap_content"
        app:layout_constraintVertical_chainStyle="packed"
        android:layout_height="wrap_content"
        app:layout_constraintVertical_bias="0"
        app:layout_constraintBottom_toTopOf="@+id/buttonTwo"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/buttonTwo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/buttonThree"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonOne" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/buttonThree"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/buttonFour"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonTwo" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/buttonFour"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/buttonFive"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonThree" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/buttonFive"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/buttonFour" />

</androidx.constraintlayout.widget.ConstraintLayout>
...