【问题标题】:android.view.InflateException Binary XML file line #54android.view.InflateException 二进制 XML 文件行 #54
【发布时间】: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

标签: android xml


【解决方案1】:

通过将 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:drawable="@drawable/clr_pressed"/> <!-- pressed -->
    <item android:state_focused="true"
          android:drawable="@android:color/transparent"/> <!-- focused -->
    <item android:drawable="@android:color/transparent"/> <!-- default -->
</selector>

并将以下内容添加到 strings.xml

<drawable name="clr_normal">#AAAAAA</drawable>
<drawable name="clr_pressed">#777777</drawable>

问题已解决,代码按预期工作。

【讨论】:

  • 我一直在尝试分配颜色属性,但正确的做法是将其分配给背景属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多