【发布时间】:2011-05-11 17:01:16
【问题描述】:
如何向按钮添加图像而不是文本?
【问题讨论】:
标签: android image button imagebutton
如何向按钮添加图像而不是文本?
【问题讨论】:
标签: android image button imagebutton
比较幽默的是,考虑到您的标签,只需使用 ImageButton 小部件。
【讨论】:
正如他所说,使用了ImageButton 小部件。将图像文件复制到项目的 Res/drawable/ 目录中。在 XML 中,只需进入 XML 文件的图形表示(为简单起见)并单击您添加的 ImageButton 小部件,转到其属性表并单击 src: 字段中的 [...]。只需导航到您的图像文件。另外,请确保您使用的是正确的格式;由于我自己的原因,我倾向于坚持使用 .png 文件,但它们确实有效。
【讨论】:
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="News Feed"
android:icon="@drawable/newsfeed" />
newsfeed 是可绘制文件夹中的图像
【讨论】:
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_text" android:drawableLeft="@drawable/button_icon">
你应该试试这样的
<Button
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/qrcode"/>
android:background="@drawable/qrcode" 会做到的
【讨论】:
wrap_content 时选择正确的大小。 Button 可以扭曲图像,尤其是在它们很小的时候。
将您的图像放入可绘制文件夹中。这里我的图片文件名是left.png
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="118dp"
android:layout_y="95dp"
android:background="@drawable/left"
android:onClick="toast"
android:text=" " />
【讨论】:
只需使用 ImageButton 视图并为其设置图像:`
<ImageButton
android:id="@+id/searchImageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:src="@android:drawable/ic_menu_search" />
【讨论】:
您可以在您的 android activity_main.xml 中创建一个 ImageButton,并且您希望将哪个图像放置在您的按钮中,只需将该图像粘贴到您的 drawable 文件夹中即可。下面的示例代码供您参考。
<ImageButton
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="49dp"
android:layout_weight="1"
android:onClick="prev"
android:src="@drawable/prev"
/>
【讨论】:
Material Components 中的新MaterialButton 可以包含一个图标:
<com.google.android.material.button.MaterialButton
android:id="@+id/material_icon_button"
style="@style/Widget.MaterialComponents.Button.TextButton.Icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/icon_button_label_enabled"
app:icon="@drawable/icon_24px"/>
您还可以自定义一些图标属性,例如iconSize 和iconGravity。
参考here。
【讨论】:
您可以将 ImageView 用作按钮。在为 ImageView 编写 imageView.setOnClickListener 之后创建一个 ImageView 并设置 clickable true。
<ImageView
android:clickable="true"
android:focusable="true"`
android:id="@+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
在Activity的oncreate中:
imageView.setOnClickListener(...
【讨论】: