添加ConstraintLayout到带Toolbar的LinearLayout后Toolbar不可见问题求助
问题根因
你遇到的问题核心是布局参数配置错误导致Toolbar被遮挡,和visibility属性无关:
- 外层是垂直方向的LinearLayout,你给动态添加的ConstraintLayout设置了高度为
MATCH_PARENT,它会直接占满整个父布局的高度,把位于它上方的Toolbar完全挤出可视区域,Layout Inspector显示的GONE属于视觉遮挡后的误判,调试器显示的VISIBLE才是真实属性状态。 - 动态添加View时你用了通用的
ViewGroup.LayoutParams,没有适配LinearLayout的布局规则,无法正确分配垂直方向的剩余空间。
修复方案
1. 修改动态添加View的布局参数
把setView方法里的addView逻辑改为使用LinearLayout专属的LayoutParams,设置weight=1让ConstraintLayout只占用Toolbar之外的剩余垂直空间,不会挤走Toolbar:
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); // 垂直LinearLayout中设置height=0 + weight=1 即可占满剩余空间 LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, 0, 1.0f ); layout.addView(view, params); }
2. 修复ConstraintLayout内的参数冲突
你当前给FragmentContainerView同时设置了layout_height="wrap_content"和app:layout_constraintBottom_toBottomOf="parent",两个规则冲突会导致Fragment内容显示异常,修改为如下配置即可让Fragment填满整个ConstraintLayout:
<androidx.fragment.app.FragmentContainerView android:id="@+id/nav_host_fragment" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="match_parent" android:layout_height="0dp" app:defaultNavHost="true" app:navGraph="@navigation/nav_graph" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent"/>
内容的提问来源于stack exchange,提问作者notReallyDev
相关产品推荐
相关产品推荐

