簡體   English   中英

如何連接約束布局中保存在不同協調器布局容器中的視圖?

[英]How to connect views in constraint layout that holds in different containers of coordinator layout?

我有一個具有主布局的CoordinatorLayout類型的片段

    <?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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">

<include
    android:id="@+id/secondContainer"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"/>

<include
    android:id="@+id/mainContainer"
    layout="@layout/view_home_content"
    app:layout_anchorGravity="bottom"/>


</androidx.coordinatorlayout.widget.CoordinatorLayout>

所以在主容器中,我得到了兩個獨立的布局。 第一

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/topContainer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <Button
        android:id="@+id/topButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</androidx.constraintlayout.widget.ConstraintLayout>

還有最下面的

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/bottomContainer"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <TextView
        android:id="@+id/bottomText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</androidx.constraintlayout.widget.ConstraintLayout>

所以我的主要目標是使帶有 id topButton約束的視圖位於bottomText的底部。 我試圖以編程方式制作它,如果它們在同一個 xml 文件中,它可以正常工作,但是當它們分開時,如我上面所示,它不起作用這是我以編程方式連接它們的方式

with(binding.topContainer) {
        topContainer = topContainer
        button = topButton
    }

    with(binding.bottomContainer) {
        text = bottomText       
    }

    val mConstraintSet = ConstraintSet()
    mConstraintSet.clone(topContainer)
    mConstraintSet.clear(R.id.topButton, ConstraintSet.TOP)
    mConstraintSet.connect(R.id.topButton, ConstraintSet.TOP, R.id.bottomText, ConstraintSet.BOTTOM)
    mConstraintSet.applyTo(topContainer)

正如我之前所說,如果我使用一個文件中的布局 ID,它會起作用。 但這樣一來,他們似乎看不到對方

預計在使用兩個單獨的文件時它不會起作用。 要使用約束,您需要將所需的視圖放在相同的約束布局中。 底部有一個 ConstraintLayout,頂部有另一個。 您可以嘗試將 ConstraintLayout 放在 coordinatorLayout 中,並嘗試將約束放在 include 標記中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM