在向后兼容的应用程序中使用?android:attr/的方法

14

我正在尝试让我的ICS(API版本15)应用程序与Gingerbread(API版本10)兼容,但是任何具有?android:attr/属性的布局XML都会出现InflateException Error inflating class <Unknown>错误。如果我注释掉这些属性,我可以编译和运行应用程序,但当然它看起来很糟糕。

我不想复制我正在使用的所有android.R.attr项,但目前我不知道另一种方法。

我正在使用ActionBarSherlock让ActionBar工作,我似乎没有使用其他需要支持库的东西(虽然在尝试解决这个问题的过程中已经包含了它),只是这些基于主题的资源让我卡住了。

我正在使用的一些主题资源是:

?android:attr/textColorSecondaryInverse ?android:attr/textAppearanceLarge ?android:attr/dividerVertical ?android:attr/selectableItemBackground ?android:attr/textAppearanceMedium ?android:attr/dividerVertical ?android:attr/dividerHorizontal


很遗憾,ABS(我的版本是4.1.0)中没有定义dividerHorizontal样式。(可能是因为它仅涵盖ActionBar使用的样式)。实际上,dividerVertical已经定义了。 ABS主题不包含所有原始样式真是令人沮丧! - WindRider
1
@WindRider 不要误导他人。请查看 Android 源代码中的 2 行。这只是一个简单的 1x1 九宫格 PNG 图像。ActionBarSherlock 也是如此。但它没有添加别名 dividerHorizontal - mente
3个回答

12

要使用API 11中的样式,特别是android:attr/textAppearanceMedium、?android:attr/dividerVertical和?android:attr/dividerHorizontal,最简单的方法是在需要的地方使用以下代码。

<!-- For Horizontal Line-->
<View
android:layout_width="match_parent"
android:layout_height="1dip"
android:layout_marginLeft="4dip"
android:layout_marginRight="4dip"
android:background="#aaa"
android:layout_alignParentTop="true"/>

<!-- For Vertical Line-->

<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="wrap_content"
android:layout_marginBottom="4dip"
android:layout_marginTop="4dip"
android:background="#aaa"/>

完美的解决方案。但是为什么需要marginLeft和marginRight?属性android:divider="?android:attr/dividerHorizontal"跨越整个屏幕宽度。 - IgorGanapolsky
我想要带有那个边距的水平线。没有边距也可以。你可以把它去掉。 - sandeep_jagtap

11

根据文档,一些样式需要更高的API。例如:

  • dividerVertical 自API 11开始
  • dividerHorizontal 自API 11开始

?标记用于引用当前主题中的样式。

要解决问题,您可以:

  • 使用API 11中的样式,但将它们放入values-v11文件夹中,并在旧版本中支持样式,使用自定义值或来自旧API的不同属性。
  • 从ICS中复制必要的样式
  • 不使用这些样式
  • 使用自定义样式

这取决于您的目标。第一个建议对于重视应用程序本地风格的人很有意义。
如果您想在所有平台上都拥有Holo样式,则没有其他办法,只能复制它并将其用作所有平台的一个样式。
请查看此项目:https://github.com/Prototik/HoloEverywhere


有没有你第一个建议的示例?我认为引用v11+上的本地样式会更好,但我不确定我需要在不同的valuesvalues-v11样式定义中放入什么来传递到v11的普通Holo资源,并为兼容版本定义特定的(我猜是复制Holo资源)。 - dsample

3
请查看Android支持V7 - AppCompat项目。它具有许多主题和属性,用于向后兼容(例如attr/dividerHorizontal)。

http://developer.android.com/tools/support-library/features.html#v7-appcompat

要使用v7支持库,您必须将其作为Android lib项目导入,并从您的项目中引用它。它还包含v4支持库,因此您可能希望在libs文件夹中删除v4支持库 :) 祝好运!

我认为这是不可能的。虽然该属性存在,但不能保证有一个用于垂直分隔线的可绘制对象。 - Tim Kist
1
可绘制对象(包括垂直分隔线)也打包在v7支持项目中,同时还有XML属性值:)。 - khigianguyen
1
请原谅,我没有看到垂直分隔符可绘制对象。它在res/drawable-mdpi/abc_list_divider_holo_(dark/light).9.png中。 - Tim Kist
我不行 :(. 我试过移除投票但是它被锁定了。我也尝试编辑它但是不起作用 :(. 抱歉。 - Tim Kist

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