如何将图像添加到按钮而不是文本?
9 回答
相当幽默,考虑到您的标签,只需使用ImageButton
小部件。
只需使用 ImageButton View 并为其设置图像:`
<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" />
正如他所说,使用了ImageButton
小部件。将图像文件复制到Res/drawable/
项目目录中。在 XML 中,只需进入 XML 文件的图形表示(为简单起见)并单击ImageButton
您添加的小部件,转到其属性表并单击src:
字段中的 [...]。只需导航到您的图像文件。另外,请确保您使用的是正确的格式;出于我自己的原因,我倾向于坚持使用 .png 文件,但它们确实有效。
你应该尝试这样的事情
<Button
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/qrcode"/>
android:background="@drawable/qrcode"
会做的
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="News Feed"
android:icon="@drawable/newsfeed" />
新闻源是可绘制文件夹中的图像
Material Components 中的 newMaterialButton
可以包含一个图标:
<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
。
参考这里。
将您的图像放在可绘制文件夹中。这里我的图片文件名是 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=" " />
您可以在您的 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"
/>
您可以使用 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(...