如何将标题放置在ImageView顶部,使用layout_above时文字不可见如何解决
解决方案
你遇到的文字不可见问题通常由两种原因导致:一是TextView添加layout_above属性后未做其他约束,被挤出父布局可视区域;二是控件声明顺序错误,TextView被后绘制的ImageView遮挡。可根据你的布局类型选择对应实现方案:
方案1:使用RelativeLayout实现(标题位于ImageView上方独立区域)
优先声明标题控件,再给ImageView添加layout_below属性绑定标题ID即可,无需给标题加layout_above:<RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/title_tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="目标标题" android:textSize="16sp" android:layout_marginBottom="8dp"/> <ImageView android:id="@+id/content_iv" android:layout_width="match_parent" android:layout_height="200dp" android:layout_below="@id/title_tv" android:scaleType="centerCrop"/> </RelativeLayout>方案2:使用RelativeLayout实现(标题叠加在ImageView内部顶部)
先声明ImageView,后声明TextView,给TextView添加layout_alignTop属性绑定ImageViewID即可,后声明的控件会绘制在上层不会被遮挡:<RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <ImageView android:id="@+id/content_iv" android:layout_width="match_parent" android:layout_height="200dp" android:scaleType="centerCrop"/> <TextView android:id="@+id/title_tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="叠层标题" android:textColor="#FFFFFF" android:layout_alignTop="@id/content_iv" android:layout_margin="12dp"/> </RelativeLayout>方案3:使用官方推荐的ConstraintLayout实现,适配性更强,不会出现顺序导致的遮挡问题:
<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/title_tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="目标标题" android:textSize="16sp" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" android:layout_marginBottom="8dp"/> <ImageView android:id="@+id/content_iv" android:layout_width="match_parent" android:layout_height="200dp" android:scaleType="centerCrop" app:layout_constraintTop_toBottomOf="@id/title_tv" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout>
内容的提问来源于stack exchange,提问作者Clark
相关产品推荐
相关产品推荐

