在按钮上展示文本
(带图片)的最佳方式
你的问题: 如何在 ImageButton
上显示 text
?
答案: 你无法使用 imageButton
显示 text
。在已接受的答案中提到的方法也无法实现。
因为
如果您使用 android:drawableLeft="@drawable/buttonok"
,则无法将 drawable
设置在 button
的 center
中。
如果您使用 android:background="@drawable/button_bg"
,则会更改您的 drawable
的颜色。
在Android世界中,有数千个选项可用于解决此问题。但是,在我看来,以下是最佳选择。
解决方案:使用带有LinearLayout
的cardView
您在
LinearLayout
中使用了
drawable/image
,因为它显示在中心。通过
textView
的帮助,您可以在其上设置
text
。我们将
cardView
背景设置为
transparent
。
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="99dp"
android:layout_margin="16dp"
app:cardBackgroundColor="@android:color/transparent"
app:cardElevation="0dp"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/your_selected_image"
>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Happy Coding"
android:textSize="33sp"
android:gravity="center"
>
</TextView>
</LinearLayout>
</androidx.cardview.widget.CardView>
这里我解释一些术语:
app:cardBackgroundColor="@android:color/transparent"
用于使cardView
的背景透明。
app:cardElevation="0dp"
用于隐藏cardView
周围的高程线。
app:cardUseCompatPadding="true"
它提供了cardView
的实际尺寸。在使用cardView
时,请始终使用此选项。
将您的image/drawable
设置为LinearLayout
的背景。
抱歉,我的英语不好。
Happy Coding :)
setCompoundDrawables*()
方法。 - Cristian