【发布时间】: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