Android布局中TextView多行文本时内容下移问题求助
Android布局中多行TextView内容下移问题分析
布局代码
<LinearLayout android:layout_marginStart="@dimen/space_10" android:layout_marginEnd="@dimen/space_10" android:layout_width="match_parent" android:layout_height="wrap_content" android:weightSum="3.2" android:orientation="horizontal"> <TextView android:id="@+id/tvDonate" android:fontFamily="@font/tajawal_medium" android:textSize="@dimen/font_size_14" android:textColor="@color/colorPrimary" android:background="@drawable/background_yellow_rounded_corner" android:gravity="center" android:layout_weight="1" android:text="@string/text_donation_title" android:layout_width="0dp" android:layout_height="@dimen/space_48"/> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0.1"/> <TextView android:id="@+id/tvRecurring" android:fontFamily="@font/tajawal_medium" android:textSize="@dimen/font_size_14" android:textColor="@color/white" android:background="@drawable/background_darkergreen_rounded_corner" android:gravity="center" android:layout_weight="1" android:text="@string/recurring_donation" android:layout_width="0dp" android:layout_height="@dimen/space_48"/> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="0.1"/> <TextView android:id="@+id/tvAddToCart" android:fontFamily="@font/tajawal_medium" android:textSize="@dimen/font_size_14" android:textColor="@color/colorPrimary" android:background="@drawable/greenborder_bg_10" android:gravity="center" android:layout_weight="1" android:text="@string/addToCart" android:layout_width="0dp" android:layout_height="@dimen/space_48"/> </LinearLayout>
问题描述
布局中的tvRecurring TextView在文本显示为两行时出现内容下移的情况,单行显示时一切正常。
问题原因
- LinearLayout默认基线对齐是核心原因:LinearLayout的
android:baselineAligned属性默认值为true,该属性会让所有子View基于文本的基线对齐。当tvRecurring显示多行文本时,其文本基线位置会比单行状态下更低,为了匹配基线,整个TextView会被向下偏移,而其他单行TextView的基线位置保持正常,因此视觉上出现多行TextView内容下移的现象。 - TextView字体内边距加剧视觉偏移:TextView默认开启
includeFontPadding(默认值为true),多行文本时字体自带的上下额外内边距会让文本在固定高度的View内的视觉位置发生细微偏移,进一步放大下移的视觉效果。
解决建议
- 给外层LinearLayout添加
android:baselineAligned="false",关闭基线对齐功能,让子View按照自身设置的gravity属性垂直居中显示。 - 可给
tvRecurring添加android:includeFontPadding="false",减少字体额外内边距,让文本在固定高度内的居中效果更精准。
内容的提问来源于stack exchange,提问作者Fahim Parkar
相关产品推荐
相关产品推荐

