You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发中ConstraintLayout运行时不显示仅展示Fragment标题如何解决

问题1:Activity布局NavHostFragment约束错误

你的activity_main.xml中NavHostFragment的底部约束配置错误,导致Fragment容器高度为0,仅能显示ActionBar的标题:

<!-- 错误写法 -->
app:layout_constraintBottom_toTopOf="parent"

将其修改为以下内容即可让Fragment容器撑满父布局:

<!-- 正确写法 -->
app:layout_constraintBottom_toBottomOf="parent"

问题2:Fragment布局控件约束缺失/冲突

ConstraintLayout要求每个子控件必须配置水平+垂直两个方向的约束才能正确布局,你当前的布局存在两个问题:

  1. et_mobile仅配置了顶部约束,缺少水平方向约束,布局时会定位异常
  2. et_first_name和btn_verify_details同时配置了顶对顶、底对底的父布局约束,两个控件会居中重叠,导致下层控件被遮挡

修正后的fragment_enter_details.xml参考:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/purple_200"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".EnterDetailsFragment">

    <EditText
        android:id="@+id/et_first_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <EditText
        android:id="@+id/et_mobile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        app:layout_constraintTop_toBottomOf="@+id/et_first_name"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"/>

    <Button
        android:id="@+id/btn_verify_details"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Verify details"
        android:layout_margin="10dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/et_mobile"/>
</androidx.constraintlayout.widget.ConstraintLayout>

可选优化:补充Binding内存泄漏防护

建议在EnterDetailsFragment中补充onDestroyView生命周期方法,清空Binding引用避免内存泄漏:

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
}

内容的提问来源于stack exchange,提问作者BRDroid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 04:24:01