问题描述
当前,我有一个充满图像的网格布局,但是我想在图像上显示一些文本,并且文本会随着时间的变化/更新。最好的选择是什么?
XML代码如下所示:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridLayout
android:id="@+id/GridLayout1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:columnCount="3"
android:rowCount="11"
android:orientation="horizontal"
tools:context=".MainActivity2" >
<Button
android:id="@+id/my_button1"
android:layout_height="wrap_content"
android:layout_columnSpan="3"
android:layout_gravity="center"
android:layout_margin="5dp"
android:layout_marginTop="700dp"
android:layout_marginBottom="40dp"
android:text="CLOSE CONNECTION" />
<ImageView
android:id="@+id/my_img1"
android:layout_width="120dp"
android:layout_height="100dp"
android:layout_margin="5dp"
android:src="@drawable/ic_svgimg_img"/>
<ImageView
android:id="@+id/my_img2"
android:layout_width="120dp"
android:layout_height="100dp"
android:layout_margin="5dp"
android:src="@drawable/ic_svgimg_img"/>
.
.
.
解决方法
为此,您可以使用FrameLayout
。尝试这样的事情
<FrameLayout>
<ImageView />
<TextView />
</FrameLayout>
FrameLayout将重叠视图,您可以通过重力播放来调整位置。如果需要更复杂的对齐方式,则可以使用更复杂的布局,例如RelativeLayout或ConstraintLayout。
,根据设计创建一个包含TextView和ImageView的自定义布局,并在xml文件中使用该自定义布局,并编写一些方法以编程方式进行更新。
,您可以单独创建gridView项,在gridView中使用这些项,并使用constraintLayout将文本放在图像上,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ImageView
android:id="@+id/button3"
android:layout_width="0dp"
android:layout_height="0dp"
android:scaleType="fitXY"
android:background="@color/colorAccent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_percent="0.2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:text="I am the text over the image"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="@+id/button3"
app:layout_constraintEnd_toEndOf="@+id/button3"
app:layout_constraintStart_toStartOf="@+id/button3" />
</androidx.constraintlayout.widget.ConstraintLayout>
它看起来像这样: