笔者最近刚学习Android开发,遇到的问题和解决办法在此分享(小白一枚,勿喷,不过欢迎批评指正)
在练习“玩安卓”UI绘制时遇到如下问题:ConstraintLayout下给ListView的约束条件失效
其中UI界面的最外层为ConstraintLayout,内部从上到下分别为导航栏、焦点轮播图、公告栏、标题栏,出现问题的layout的伪代码如下所示:
<ConstraintLayout>
<LinearLayout android:id="@+id/navigation_bar" .../>
<RelativeLayout android:id="@+id/focus_scoll" .../>
<ListView android:id="@+id/bulletin_board"
android:layout_width="match_parent"
android:layout_height="wrap_parent"
app:layout_constraintBottom_toTopOf="@id/title_bar"
app:layout_constraintTop_toBottomOf="@id/focus_scoll".../>
<BottomNavigationView android:id="@+id/title_bar" .../>
</ConstarintLayout>
如上所示代码,虽然约束了公告栏的上下边界,但其上边界和下边界仍然会超出轮播图的下边界和标题栏的上边界,显然是不合理的。
后查阅相关博客,解释说是因为ListView、RecycleView等ScrollView类型,会默认以父组件右上角作为Start、Top边界,并提出在ListView外套一层ConstraintLayout并设置该Layout的heigth=0dp解决,解释为:不指定高度,ListView会默认有空间可以扩展,设置0dp的高度会迫使ListView限制在约束条件中。
上述方法确实可以解决,不过加ConstraintLayout有些多余,笔者通过直接设置ListView的height为0dp也可以实现同样效果,因此笔者认为多加一层ConstraintLayout并非主要因素,限制ListView扩展高度才是关键:
<ListView android:id="@+id/bulletin_board"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@id/title_bar"
app:layout_constraintTop_toBottomOf="@id/focus_scoll".../>