首页 > 解决方案 > 添加 ConstraintLayout 后工具栏不可见

问题描述

我正在使用工具栏将 ConstraintLayout 添加到 LinearLayout。添加 ConstraintLayout 会导致工具栏不再可见,并且 Layout Inspector 显示工具栏具有可见性,GONE尽管调试器显示VISIBLE. 我在这里错过了什么吗?使用LayoutParams.WRAP_CONTENT也不行。

    protected void setView(View view) {
            super.setContentView(R.layout.content_view);

            toolbar = findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            LinearLayout layout = findViewById(R.id.linear_layout);
            layout.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        }

内容视图.xml:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/linear_layout"
    android:orientation="vertical">
    <include layout="@layout/toolbar"/>
</LinearLayout>

传入的视图:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@color/white">
    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph"
        app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

标签: androidandroid-layout

解决方案


你有一些你可能会丢失的东西。

  1. 图片不完整 - 为什么要动态添加视图?尝试将其添加到布局 xml 中<include layout="@layout/[NAME_OF_THE_VIEW_LAYOUT]"/>并注释掉 java 代码 - 只是为了确定。
  2. 您正在添加到 LinearLayout,但使用 ViewGroup.LayoutParams,这是不行的,请改用 LinearLayout.LayoutParams。
  3. 这可能与缺少的工具栏无关,但在 ConstraintLayout 内部可能没有任何内容。放置一个简单的文本视图或将颜色更改为非常明显的颜色(例如#00F)以确保添加它。

推荐阅读