【问题标题】:Error inflating class android.widget.Button with custom selector使用自定义选择器膨胀类 android.widget.Button 时出错
【发布时间】:2016-01-07 10:51:13
【问题描述】:

我正在尝试在 android 视图中设置按钮的样式,但由于添加了自定义选择器,我收到以下错误,这是什么原因造成的?:

Android.Views.InflateException: Binary XML file line #1: Error inflating class android.widget.Button

导致悲伤的观点

<Button
    android:text="Next"
    android:id="@+id/nextButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    style="@style/primary_button_style"
    android:textColor="@color/button_primary"
    android:background="@color/button_primary" />

res/color/button_primary.xml

<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item
    android:color="@color/accent"
    android:state_enabled="true"
    />
  <item
    android:color="@color/grey"
    android:state_enabled="false"
    />
</selector>

res/values/Styles.xml

  <style name="primary_button_style" parent="android:Widget.Button">
    <item name="android:paddingLeft">50px</item>
    <item name="android:paddingRight">50px</item>
    <item name="android:height">50px</item>
    <item name="android:minHeight">50px</item>
    <item name="android:maxHeight">50px</item>
    <item name="android:textAllCaps">true</item>
    <item name="android:textSize">30px</item>
    <item name="android:textStyle">bold</item>
  </style>

我在 Visual Studio 中使用 Xamarin

【问题讨论】:

  • 将选择器放入drawable文件夹并像android:background="@drawable/button_primary"一样添加

标签: android xml xamarin


【解决方案1】:

您发布的选择器适用于文本颜色,而不适用于背景。您应该在文件夹drawable/ 中添加一个并使用android:drawable 而不是android:color

<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item
    android:drawable="@color/accent"
    android:state_enabled="true"
    />
  <item
    android:drawable="@color/grey"
    android:state_enabled="false"
    />
</selector>

顺便说一句。如果你对背景和文本使用相同的颜色,你将看不到后者

【讨论】:

  • 我的按钮在android:state_enabled="false"="true" 上有不同的颜色文本和背景。我应该为背景(使用您的示例)和文本颜色(使用我现有的文件)使用单独的选择器文件吗?
  • 是的,你必须这样做。我的只是基于您发布的内容的示例。用“真实”的颜色替换颜色
  • 非常感谢,我打算扩展我为文本颜色和背景发布的单个选择器。感谢您解决这个问题。
【解决方案2】:

致电drawable instead of color

你得到了

Android.Views.InflateException:二进制 XML 文件第 1 行:错误 膨胀类 android.widget.Button

问题来了

 android:background="@color/button_primary"

您可以创建drawable文件夹并调用

android:background="@drawable/button_primary"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多