如何通过Android主题设置任何窗口小部件的宽度/高度

8

我需要在多个屏幕(xml)中使用具有相同属性的相同小部件(按钮、编辑框、文本视图),如宽度、高度、文本颜色、大小等。因此,我为各个小部件创建了样式(一个用于按钮,一个用于编辑框...),并在我的CustomTheme中定义了所有这些样式。

我的问题是

如果我在样式中定义了布局宽度/高度,并在xml中简单地给出style="@style/myButtonStyle",则按钮将正常工作,即使我没有在xml中指定宽度/高度(可能是从样式继承)。

如果我在xml中不使用样式属性而只是简单地将我的自定义主题提供给活动,则会引入我在主题中指定的所有样式。但如果我没有在xml中指定宽度/高度,它会引发异常,说明您必须指定布局宽度/高度,而我已经在样式本身中指定了。

我的主题文件如下

 <style name="Theme.Blue" parent="android:Theme">
 <item name="android:buttonStyle">@style/button222</item>
<item name="android:textViewStyle">@style/text222</item>
<item name="android:editTextStyle">@style/edittext222</item>
</style>

我的按钮222的样式是

 <style name="button222" parent="@android:style/Widget.Button">
<item name="android:layout_width">@dimen/mWidth</item>
<item name="android:textColor">#F56266</item>
<item name="android:textSize">20sp</item>
</style>

我把尺寸规定为
       <dimen name="mWidth">180dip</dimen>

我在layout.xml中这样使用:

                          <Button   android:layout_width="180dip"
                android:layout_height="wrap_content"
                android:text="This is large text."
                />

            <Button
                android:layout_height="wrap_content"
                android:text="This is regular text one"
                />

            <Button
                style="@style/button222"
                android:layout_height="wrap_content"
                android:text="This is regular text."
                />

它报错说要指定布局宽度,但我在button222样式中已经指定了,并尝试通过我的主题使用。

3个回答

10

您应该在样式XML中插入一个尺寸值:

<dimen name="buttonHeight">40px</dimen>

然后,您只需引用尺寸值。因此,在您的布局文件中,您将编写:

android:layout_height="@dimen/buttonHeight"

4
所以每个按钮仍然需要编写 android:layout_height="@dimen/buttonHeight" 吗?这样怎么能缩短它呢? - woojoo666

1
只需通过应用程序主题引用样式,此错误将消失。操作步骤如下:
style="@style/Theme.blue"

0

不确定您的目标是什么:您是否重视避免在layout.xml文件中提及layout_widthlayout_height,还是只是寻找任何一种使用主题值而不引用个别样式的方法?

在后一种情况下,解决方案如下:

layout_width="?attr/myCustomWidth"

在您的CustomTheme中定义了一个属性myCustomWidth


谢谢,@marc1s。我希望可以避免在layout.xml文件中使用layout_width和layout_height。 - Ganesh K
是的,原因是将所有按钮、文本字段或其他定义都放在样式定义中,而不是部分在那里,部分在某些值文件中。 - Lassi Kinnunen

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