【发布时间】:2021-02-04 05:25:16
【问题描述】:
我正在尝试向我的 Activity 动态添加一个片段,该片段将在它被放入的约束布局内具有某些约束。
简而言之,我想要将片段添加到约束布局。约束布局具有覆盖整个屏幕的边界,但顶部有一个标题。我希望 Fragment 具有带有 Header 的 Top-Bottom 约束和带有父 Constraint Layout 的 Bottom-Bottom 约束的约束
我尝试将约束放入片段的布局 XML 我尝试使用 ConstraintSet 以编程方式设置约束
活动布局 XML(主活动)
<android.support.constraint.ConstraintLayout
android:id="@+id/main_activity_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.seven.eleven.ideation.views.HeaderLayout
android:id="@+id/header"
android:layout_width="match_parent"
android:layout_height="@dimen/header_height"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
活动代码
getSupportFragmentManager().beginTransaction()
.add(R.id.main_activity_layout, homeFragment, HOME_TAG).commit();
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(mainLayout);
constraintSet.connect(R.id.fragment_home_root, ConstraintSet.TOP,
R.id.header, ConstraintSet.BOTTOM);
constraintSet.connect(R.id.fragment_home_root, ConstraintSet.BOTTOM,
R.id.root, ConstraintSet.BOTTOM);
constraintSet.applyTo(mainLayout);
片段布局 XML(主页片段)
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/fragment_home_root"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="@+id/header"
app:layout_constraintBottom_toBottomOf="parent">
<TextView
android:id="@+id/welcome_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="@+id/welcome_paragraph_text"
android:layout_margin="@dimen/box_margins"
android:text="@string/welcome"
android:textSize="@dimen/oversized_text_size"
android:textColor="@color/primary_text_color"
android:textStyle="bold"/>
<TextView
android:id="@+id/welcome_paragraph_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginLeft="@dimen/box_margins"
android:layout_marginRight="@dimen/box_margins"
android:text="@string/welcome_paragraph"
android:textSize="@dimen/primary_text_size"
android:textColor="@color/primary_text_color"/>
</android.support.constraint.ConstraintLayout>
根据我使用的方法,Fragment 要么位于顶部,要么位于整个屏幕的中心,而不是被限制在 Header 的底部
【问题讨论】:
标签: android android-constraintlayout