android button如何添加图标
时间: 2023-10-13 12:07:36 浏览: 70
在 Android Button 上添加图标的方法有两种:
1. 在 XML 文件中设置
可以在 Button 标签中使用 android:drawableLeft、android:drawableRight、android:drawableTop 或 android:drawableBottom 属性设置图标的位置,例如:
```xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button with icon"
android:drawableLeft="@drawable/icon" />
```
其中,@drawable/icon 是你的图标资源文件的名称。
2. 在代码中设置
可以使用 setCompoundDrawables() 方法在代码中设置 Button 的图标,例如:
```java
Button button = findViewById(R.id.button);
Drawable icon = getResources().getDrawable(R.drawable.icon);
button.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
```
其中,R.drawable.icon 是你的图标资源文件的名称。通过 setCompoundDrawablesWithIntrinsicBounds() 方法可以设置图标的位置,第一个参数是左边的图标,第二个参数是上面的图标,第三个参数是右边的图标,第四个参数是下面的图标。如果只想设置一个图标,则其他参数传入 null 即可。