【发布时间】:2013-10-16 17:06:38
【问题描述】:
我有一个 ImageButton,我想制作它,以便在按下按钮时按钮背景会改变颜色。我已经从this question 中复制了 button_bg.xml 文件。
button_bg.xml 看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:color="#ffff0000"/> <!-- pressed -->
<item android:state_focused="true"
android:color="#ff0000ff"/> <!-- focused -->
<item android:color="#ff000000"/> <!-- default -->
</selector>
第 54 行如下所示:
<ImageButton
android:id="@+id/sendButton"
android:background="@drawable/button_bg"
android:src="@drawable/ic_action_send_now"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="4dp"
android:layout_alignParentRight="true" />
我已尝试删除该行:
android:background="@drawable/button_bg"
这会阻止应用程序崩溃,但按钮不会改变颜色。
任何帮助将不胜感激
【问题讨论】:
-
您在哪个版本的 Android 上进行测试?我怀疑问题出在
android:src,而不是android:background。 -
尝试在 setContentView() 调用之前将 Drawable x = getResources().getDrawable(R.drawable.button_bg"); 添加到您的 Activity#onCreate() 方法中。如果它有效,那么您的 drawable 就可以了. 如果失败,您可能会在 logcat 中收到更好的错误消息。
-
在堆栈跟踪中的 InflateException 下方,可能存在描述特定问题的“由”异常“引起”。请在问题中包含完整的堆栈跟踪。
-
第一个原因如下:java.lang.reflect.InvocationTargetException。后面的下一个是 Caused by: android.content.res.Resources$NotFoundException: File res/drawable/button_bg.xml from drawable resource ID #0x7f020001