ConstraintLayout: Einschränkungen programmgesteuert ändern

Lesezeit: 9 Minuten

ConstraintLayout Einschrankungen programmgesteuert andern
Großer Trainer

Ich brauche Hilfe bei ConstraintSet. Mein Ziel ist es, die Einschränkungen der Ansicht im Code zu ändern, aber ich kann nicht herausfinden, wie ich das richtig mache.

ich habe 4 TextViews und eins ImageView. Ich muss einstellen ImageView Einschränkungen zu einem der TextViewS.

check_answer4 = (TextView) findViewById(R.id.check_answer4);
check_answer1 = (TextView) findViewById(R.id.check_answer1);
check_answer2 = (TextView) findViewById(R.id.check_answer2);
check_answer3 = (TextView) findViewById(R.id.check_answer3);

correct_answer_icon = (ImageView) findViewById(R.id.correct_answer_icon);

Wenn die erste Antwort richtig ist, muss ich Einschränkungen festlegen ImageView zu

app:layout_constraintRight_toRightOf="@+id/check_answer1"
app:layout_constraintTop_toTopOf="@+id/check_answer1"

Wenn die zweite Antwort richtig ist, muss ich Einschränkungen festlegen ImageView zu

app:layout_constraintRight_toRightOf="@+id/check_answer2"
app:layout_constraintTop_toTopOf="@+id/check_answer2"

Und so weiter.

  • Dazu müssen Sie die Einschränkung dynamisch ändern.

    – Shweta Chauhan

    23. Juli 2017 um 8:46 Uhr

  • @shweta Ich frage genau danach, wie geht das dynamisch?

    – Großer Trainer

    23. Juli 2017 um 8:49 Uhr

  • bekommen. deine Antwort posten.

    – Shweta Chauhan

    23. Juli 2017 um 8:51 Uhr


ConstraintLayout Einschrankungen programmgesteuert andern
vishakha yeolekar

  1. So legen Sie Einschränkungen für die Bildansicht fest:

     app:layout_constraintRight_toRightOf="@+id/check_answer1"
     app:layout_constraintTop_toTopOf="@+id/check_answer1"
    

    verwenden:

     ConstraintLayout constraintLayout = findViewById(R.id.parent_layout);
     ConstraintSet constraintSet = new ConstraintSet();
     constraintSet.clone(constraintLayout);
     constraintSet.connect(R.id.imageView,ConstraintSet.RIGHT,R.id.check_answer1,ConstraintSet.RIGHT,0);
     constraintSet.connect(R.id.imageView,ConstraintSet.TOP,R.id.check_answer1,ConstraintSet.TOP,0);
     constraintSet.applyTo(constraintLayout);
    
  2. So legen Sie Einschränkungen für die Bildansicht fest:

     app:layout_constraintRight_toRightOf="@+id/check_answer2"
     app:layout_constraintTop_toTopOf="@+id/check_answer2"
    

    verwenden:

     ConstraintLayout constraintLayout = findViewById(R.id.parent_layout);
     ConstraintSet constraintSet = new ConstraintSet();
     constraintSet.clone(constraintLayout); 
     constraintSet.connect(R.id.imageView,ConstraintSet.RIGHT,R.id.check_answer2,ConstraintSet.RIGHT,0);      
     constraintSet.connect(R.id.imageView,ConstraintSet.TOP,R.id.check_answer2,ConstraintSet.TOP,0);
     constraintSet.applyTo(constraintLayout);
    

  • ConstraintSet.clone (constraintLayout); Ist in dieser Zeile ConstraintLayout das übergeordnete Layout?

    – Reejesh PK

    6. Oktober 2018 um 9:21 Uhr

  • @Stich .clone(constraintLayout) Was ist diese Variable und woher bekomme ich sie?

    – Leonheess

    19. Oktober 2018 um 15:15 Uhr

  • @ReejeshPK @MiXT4PE Ja, es IST das übergeordnete Layout, dh ConstraintLayout constraintLayout = findViewById(R.id.parent_layout);

    – Muhammad Muzammil

    23. November 2018 um 7:21 Uhr

  • @leonheess Ich denke, das sollte eine Variable sein, die auf Ihre Constraint Layout ViewGroup verweist

    – Begünstige Felix Chinemerem

    23. Mai 2020 um 16:10 Uhr

  • 10 verschiedene Dinge ausprobiert und das hat funktioniert. Danke!

    – Code Wiget

    28. September 2020 um 21:10 Uhr

Angenommen, wir möchten die Einschränkungen während der Laufzeit ändern, sodass button1 beim Klicken an button2 ausgerichtet wird:

Geben Sie hier die Bildbeschreibung ein

Dann mit diesem Layout:

<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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/root"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">


    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 1"
        app:layout_constraintTop_toTopOf="@+id/button3"
        app:layout_constraintBottom_toBottomOf="@+id/button3"
        app:layout_constraintStart_toEndOf="@+id/button3"
        android:layout_marginStart="0dp"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginEnd="0dp" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:text="Button 2"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginStart="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginEnd="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintVertical_bias="0.5" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:text="Button 3"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginStart="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginEnd="8dp"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintVertical_bias="0.223" />
</android.support.constraint.ConstraintLayout>

Wir können Folgendes tun:


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

        button1.setOnClickListener {
            val params = button1.layoutParams as ConstraintLayout.LayoutParams
            params.leftToRight = button2.id
            params.topToTop = button2.id
            params.bottomToBottom = button2.id
            button1.requestLayout()
        }
    }

  • Mein Freund, ich verstehe deinen Code nicht.. was ist layoutParams und val? Ist das überhaupt Java?

    – Leonheess

    19. Oktober 2018 um 15:18 Uhr


  • Sir, es ist die Programmiersprache Kotlin. Java-Äquivalent wird sein ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) button1.getLayoutParams();

    – Azizbekisch

    19. Oktober 2018 um 19:02 Uhr

  • Ich glaube, Sie haben vergessen, button1.layoutParams = params zu schreiben

    – Sumit Sonawane

    20. Mai 2019 um 10:52 Uhr

  • @sumitsonawane, es wird nicht benötigt, weil wir diese Instanz mutieren und danach auftreten button1.requestLayout() die dann die Instanz von inspizieren wird LayoutParams dass wir mutiert sind.

    – Azizbekisch

    20. Mai 2019 um 11:48 Uhr

  • @azizbekian, ja, für mich ist die endgültige Lösung das Ersetzen requestLayout() mit anrufen setLayoutParams() und dann funktioniert es. Einfach mutieren layoutParams und das Anfordern des Layouts selbst scheint nicht auszureichen.

    – qwertyfinger

    10. Juli 2019 um 7:09 Uhr

Ein anderer Ansatz besteht darin, die Layoutparameter der Ansicht wie folgt zu aktualisieren (ohne das Layout anzufordern):

yourView.updateLayoutParams<ConstraintLayout.LayoutParams> {
        startToEnd = otherView.id
        topToTop = otherView.id
        bottomToBottom = otherView.id
        //add other constraints if needed
      }

Lassen Sie mich zusätzlich zu Azizbekians Antwort auf zwei Dinge hinweisen:

  1. Wenn links/rechts nicht funktioniert hat, versuchen Sie Start/Ende wie folgt:

params.startToEnd = button2.id

  1. Wenn Sie eine Einschränkung entfernen möchten, verwenden Sie das UNSET-Flag wie folgt:

params.startToEnd = ConstraintLayout.LayoutParams.UNSET

In Kotlin kann man einfach verlängern ConstraintSet class und fügen Sie einige Methoden hinzu, um dsl in Kotlin zu nutzen und einen besser lesbaren Code zu erzeugen. So was

class KotlinConstraintSet : ConstraintSet() {

    companion object {
        inline fun buildConstraintSet(block:KotlinConstraintSet.()->Unit) =
            KotlinConstraintSet().apply(block)
    }
    //add this if you plan on using the margin param in ConstraintSet.connect
    var margin: Int? = null
        get() {
            val result = field
            margin = null //reset it to work with other constraints
            return result
        }

    inline infix fun Unit.and(other: Int) = other // just to join two functions

    inline infix fun Int.topToBottomOf(bottom: Int) =
        margin?.let {
            connect(this, TOP, bottom, BOTTOM, it)
        } ?: connect(this, TOP, bottom, BOTTOM)

    inline fun margin(margin: Int) {
        this.margin = margin
    }

    inline infix fun Int.bottomToBottomOf(bottom: Int) =
        margin?.let {
            connect(this, BOTTOM, bottom, BOTTOM, it)
        } ?: connect(this, BOTTOM, bottom, BOTTOM)

    inline infix fun Int.topToTopOf(top: Int) =
        margin?.let {
            connect(this, TOP, top, TOP, it)
        } ?: connect(this, TOP, top, TOP)

    inline infix fun Int.startToEndOf(end: Int) =
        margin?.let {
            connect(this, START, end, END, it)
        } ?: connect(this, START, end, END)

            ...
    //TODO generate other functions depending on your needs

    infix fun Int.clear(constraint: Constraints) =
        when (constraint) {
            Constraints.TOP -> clear(this, TOP)
            Constraints.BOTTOM -> clear(this, BOTTOM)
            Constraints.END -> clear(this, END)
            Constraints.START -> clear(this, START)
        }

    //inline infix fun clearTopCon
    inline infix fun appliesTo(constraintLayout: ConstraintLayout) =
        applyTo(constraintLayout)

    inline infix fun clones(constraintLayout: ConstraintLayout) =
        clone(constraintLayout)

    inline fun constraint(view: Int, block: Int.() -> Unit) =
        view.apply(block)
}

enum class Constraints {
    TOP, BOTTOM, START, END //you could add other values to use with the clear fun like LEFT
}

Und benutze es so

        buildConstraintSet {
            this clones yourConstraintLayout
            constraint(R.id.view1) {
                margin(value:Int) and this topToBottomOf R.id.view2
                margin(30) and this bottomToBottomOf ConstraintSet.PARENT_ID
            }
            constraint(R.id.view2) {
                this clear Constraints.BOTTOM
                margin(0) and this topToTopOf R.id.topGuide
            }
            constraint(R.id.view4) {
                this topToTopOf R.id.view2
                this bottomToBottomOf R.id.view3
                this startToEndOf R.id.view2
            }
            //or you could simply do
            R.id.view1 startToEndOf R.view2
            R.id.view1 toptToBottomOf R.view3
            R.id.view3 bottomtToBottomOf R.view2
            R.id.view3 clear Constraints.END

            // and finally call applyTo()
            this appliesTo yourConstraintLayout
        }

1645913588 11 ConstraintLayout Einschrankungen programmgesteuert andern
Gefallen Felix Chinemerem

Ich weiß, dass meine Antwort sehr spät kommt, aber ich bin sicher, dass es anderen helfen würde, die hier oft vorbeischauen. Dieser Artikel ist nicht von mir, aber ich habe ein paar Änderungen vorgenommen. Davon abgesehen sollten Sie sich bemühen, den vollständigen Artikel zu lesen Hier

Beschränkungssätze

Der Schlüssel zum Arbeiten mit Constraint-Sets in Java-Code ist die ConstraintSet-Klasse. Diese Klasse enthält eine Reihe von Methoden, die Aufgaben wie das Erstellen, Konfigurieren und Anwenden von Einschränkungen auf eine ConstraintLayout-Instanz ermöglichen. Außerdem können die aktuellen Beschränkungen für eine ConstraintLayout-Instanz in ein ConstraintSet-Objekt kopiert und verwendet werden, um dieselben Beschränkungen auf andere Layouts (mit oder ohne Änderungen) anzuwenden.

Eine ConstraintSet-Instanz wird wie jedes andere Java-Objekt erstellt:

ConstraintSet set = new ConstraintSet();

Nachdem ein Constraint-Set erstellt wurde, können Methoden für die Instanz aufgerufen werden, um eine Vielzahl von Aufgaben auszuführen. Der folgende Code konfiguriert einen Constraint-Satz, in dem die linke Seite einer Button-Ansicht mit der rechten Seite einer EditText-Ansicht mit einem Rand von 70 dp verbunden ist:

set.connect(button1.getId(), ConstraintSet.LEFT, 
        editText1.getId(), ConstraintSet.RIGHT, 70);

Anwenden von Beschränkungen auf ein Layout Sobald der Beschränkungssatz konfiguriert ist, muss er auf eine ConstraintLayout-Instanz angewendet werden, bevor er wirksam wird. Ein Beschränkungssatz wird über einen Aufruf der Methode applyTo() angewendet, wobei eine Referenz auf das Layoutobjekt übergeben wird, auf das die Einstellungen angewendet werden sollen:

set.applyTo(myLayout);

Es gibt noch viel mehr Sachen, die Sie mit dem machen können ConstraintSet API, horizontale und vertikale Neigung einstellen, horizontal und vertikal zentrieren, Chains manipulieren und vieles mehr.

Wirklich schön zu lesen.

Auch dies ist nur eine Adaption.

1645913589 888 ConstraintLayout Einschrankungen programmgesteuert andern
Nitin Patel

@vishakha yeolekar s Lösung funktioniert bei mir nicht.

Um Einschränkungen zu ändern, müssen wir die folgenden Schritte ausführen:

  • Klon übergeordnetes Layout
  • klar vorherige Einschränkung
  • anschließen Zwang
  • anwenden Beschränkung auf übergeordnetes Layout

Lösungscode (in Kotlin)

val clParent = findViewById<ConstraintLayout>(R.id.parent_layout)
val mConstraintSet = ConstraintSet()
mConstraintSet.clone(clParent)
mConstraintSet.clear(R.id.imageView, ConstraintSet.END)
mConstraintSet.connect(R.id.imageView, ConstraintSet.END, R.id.check_answer, ConstraintSet.END)
mConstraintSet.applyTo(clParent)

Hier ist der Link für weitere Informationen und Methoden von ConstraintSet – Klicken Sie hier.

868780cookie-checkConstraintLayout: Einschränkungen programmgesteuert ändern

This website is using cookies to improve the user-friendliness. You agree by using the website further.

Privacy policy