Android中如何让TextView在布局内垂直居中同时保持布局可滚动
解决方案
核心实现思路是外层嵌套ScrollView并开启fillViewport属性,既保证内部布局可以撑满全屏让text_no_items垂直居中,内容超过屏幕高度时又能自动滚动:
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/description" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="This is a sample description about the items you will see below. This text could be very long." android:textSize="32sp" /> <TextView android:id="@+id/text_no_items" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="1" android:layout_gravity="center_horizontal" android:gravity="center" android:text="No items" android:textSize="48sp" /> </LinearLayout> </ScrollView>
关键配置说明
android:fillViewport="true":该属性让ScrollView的子布局强制占满ScrollView的可用高度,这是让内部LinearLayout的layout_weight属性生效的前提- 当
description内容较短时,内部LinearLayout高度等于屏幕高度,text_no_items通过layout_weight="1"占满剩余高度,自带的gravity="center"会让文字垂直居中 - 当
description内容过长时,内部LinearLayout高度会超过屏幕高度,ScrollView自动进入可滚动状态,用户可以滑动查看完整内容
可选ConstraintLayout实现方案
如果你更习惯用约束布局,也可以用以下写法,逻辑更清晰:
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/description" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="This is a sample description about the items you will see below. This text could be very long." android:textSize="32sp" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"/> <TextView android:id="@+id/text_no_items" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="No items" android:textSize="48sp" app:layout_constraintTop_toBottomOf="@id/description" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintVertical_bias="0.5"/> </androidx.constraintlayout.widget.ConstraintLayout> </ScrollView>
内容的提问来源于stack exchange,提问作者Mohit Yadav
相关产品推荐
相关产品推荐

