在安卓系统中如何为按钮设置背景图片?

8

我在drawable-mdpi文件夹中导入了一张图片,然后从按钮中实现该图片,但是出现了错误no resource found here。我该如何解决这个问题?

我尝试了以下方法:

main.xml

  <Button
        android:id="@+id/imageButtonSelector"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable-mdpi/button_focused_orange"/>

enter image description here


1
由于您是新来的,您可以通过点击小的“打勾”箭头来接受答案。这将增加您的接受率,甚至帮助其他遇到类似问题的人。 - Mahendra Liya
4个回答

22

所有的可绘制对象都被编译到一个资源名称下,即drawable。 Android会根据屏幕尺寸自动选择从哪个文件夹中获取可绘制对象,因此您无需特别指出。同样,强制Android使用特定文件夹中的资源有点违背了为Android提供多个选择的目的。要解决此问题,只需更改:

    android:background="@drawable-mdbi/button_focused_orange"/>
    android:background="@drawable/button_focused_orange"/>

现在是一个去Project->Clean的好时机。同时,请确保你的Java文件中没有import android.R;这种类型的行。 - Raghav Sood
谢谢您的回复,我现在清理了项目并删除了android.R,然后运行应用程序,但是仍然出现相同的错误。 - SampathKumar
你不可能在运行时获得构建错误。请检查LogCat以查看您遇到的错误。 - Raghav Sood
当我将图像导入drawable文件夹时,会出现该错误。 - SampathKumar
请问,我添加了一张图片后出现了错误,请问需要什么格式的文件? - SampathKumar
显示剩余4条评论

4
应该使用@drawable/button_focused_orange而不是@drawable-mdpi/button_focused_orange

我有一个疑问,你能帮忙吗? - SampathKumar
错误出现在源文件中,R 无法解析为变量。 - SampathKumar

0
尝试清理和重建您的项目。 如果您正在使用Eclipse,可以通过单击项目-> 清理,然后项目-> 构建项目来执行此操作。

1
他的XML文件存在问题。仅仅清理项目而不解决问题是没有任何改变的。 - Raghav Sood
1
有时候清理一下Android构建过程中的缓存就能解决问题。当你遇到困难时,这确实是一个值得尝试的方法。 - Philippe Girolami
@RaghavSood 你说得对,我没有注意到那个。我保留了我的答案,因为_bitbox_所说的话。 - Mark

0
你不需要提及-mdpi来添加背景图片,只需使用drawable即可。这是你修改后的代码。试试看吧。
<Button
    android:id="@+id/imageButtonSelector"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/button_focused_orange"/>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接