如何使用可绘制的src创建ImageButton



我在一个名为gray_button.xml:的可绘制文件中有以下内容

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<size
android:width="300dp"
android:height="300dp" />
<solid android:color="#666"/>
</shape>
</selector>

在我的应用程序的主布局中,我有以下部分

<ImageButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:src="@drawable/gray_button"
android:layout_margin="160dp"
/>

不幸的是,按钮显示为一个小矩形,而不是椭圆形。我确信我做了一些愚蠢的事。

如何使我的按钮正确显示绘图?


更新:根据给出的答案,我将绘图框切换到了下面,但现在它只显示为一个大矩形,而不是椭圆形。

<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<size
android:width="300dp"
android:height="300dp" />
<solid android:color="#000"/>
</shape>

问题是你的形状,你使用的选择器有一个重复的URI,所以删除选择器,只使用形状:

<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<size
android:width="300dp"
android:height="300dp" />
<solid android:color="#666"/>
</shape>

通过这种方法,你会看到矩形,因为它是背景按钮,你可以绘制成图像。

尝试删除选择器和边距android:layout_margin="160dp"

这应该有效:

<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<size
android:width="300dp"
android:height="300dp" />
<solid android:color="#666"/>
</shape>
<ImageButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/gray_button"/>

我建议在简单的Button上尝试,而不是在ImageButton上。如果它仍然不起作用,那么问题可能出现在gray_button.xml文件中,否则没问题。

最新更新