【问题标题】:Inheriting Required XML Attributes from Custom Theme从自定义主题继承所需的 XML 属性
【发布时间】:2011-11-13 09:38:51
【问题描述】:

问题:

我有几个 TextView 共享大量相同的属性。我想将以下样式应用于所有 TextView。

<!-- TextView -->
<style name="fieldLabel" parent="@android:style/Widget.TextView">
    <item name="android:layout_width">fill_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_weight">0.7</item>
    <item name="android:textSize">18sp</item>
</style>

但由于某种原因,当我将此样式应用为活动范围的主题时,我收到此错误:

09-08 15:57:17.034: ERROR/AndroidRuntime(5269): Caused by: java.lang.RuntimeException: Binary XML file line #38: You must supply a layout_width attribute.

只有在我尝试将此样式应用为主题时发生。因为,当我添加

style="@style/fieldLabel"

对于每个 TextView 的属性,它都按预期工作,因此错误来自尝试将此主题应用于 整个活动。


代码:

styles.xml:

<style name="CustomActivityStyle" parent="android:Theme"> <!--This is theme I am trying to apply -->
    <item name="android:textViewStyle">@style/fieldLabel</item>
</style>

<!-- TextView -->
<style name="fieldLabel" parent="@android:style/Widget.TextView">
    <item name="android:layout_width">fill_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_weight">0.7</item>
    <item name="android:textSize">18sp</item>
</style>

myactivity.xml:

<!-- This is an example of one of the TextViews -->
<TextView
    android:id="@+id/name_label"
    android:text="@string/name_label"
/>

AndroidManifest.xml:

<!-- Implementing the theme in the Manifest -->
<activity android:name=".MyActivity"
    android:configChanges="orientation"
    android:theme="@style/CustomActivityStyle"
    android:label="@string/my_title">
</activity>

关于这个问题here 有另一个帖子,但我决定提出一个新问题而不是恢复旧问题。

总结:

我知道我可以通过简单地添加 layout_width 和 layout_height 属性来轻松完成这项工作,通过显式添加 style="@style/fieldLabel" 到每个 TextView。但这个问题的重点更多是为了改进我(希望是其他人)的编码约定,以及使代码本身更具可读性和可重用性。

实际上我很惊讶以前没有人遇到过这个问题,而且这不是一种标准的格式化方式。

感谢您的帮助。

【问题讨论】:

  • 这通常是与布局相关的异常,您能否发布完整的堆栈跟踪和布局文件。
  • @Dan 我已经编辑了我的原始问题以包含完整的堆栈跟踪和整个布局文件。感谢您的帮助!

标签: android xml android-layout android-widget


【解决方案1】:

这就是问题所在:

引起:java.lang.RuntimeException:二进制 XML 文件第 20 行:您 必须提供 layout_width 属性。

您的 TextView id name_label,需要 android:layout_heightandroid:layout_width 属性。

【讨论】:

  • 是的,但我使用自定义主题同时提供 layout_height 和 layout_width,该主题应适用于活动中的所有文本视图。那么问题来了,为什么他们没有正确继承这些字段呢?
  • 我从未见过有人通过样式应用高度和宽度。每个 TextView 都需要自己的 style 属性吗?
  • 如果我明确地将样式属性添加到每个 TextView 它将起作用,但我希望通过使用清单中的 android:theme 属性将样式添加到整个 Activity 来避免这种情况。我看不出这不应该起作用的任何原因,因此是我最初的问题。感谢您的帮助!
猜你喜欢
  • 2011-06-25
  • 2011-01-31
  • 2012-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多