【问题标题】:How to set width/height for any widget through Theme in Android如何通过Android中的主题为任何小部件设置宽度/高度
【发布时间】:2017-03-18 14:09:43
【问题描述】:

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

我的问题是

如果我也在样式中定义布局宽度/高度,并且简单地为 xml 中的按钮提供 style="@style/myButtonStyle" 工作正常,即使我没有在 xml 中提及宽度/高度(可能继承自 Style )。

如果我在没有样式属性的情况下在 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>

我的 button222 样式是

 <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 样式中提到并尝试通过我的主题使用。

【问题讨论】:

    标签: android themes


    【解决方案1】:

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

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

    那么您只需引用维度值即可。所以在你的布局文件中你会写:

    android:layout_height="@dimen/buttonHeight"
    

    【讨论】:

    • 所以你还需要为每个按钮写android:layout_height="@dimen/buttonHeight"?这如何缩短它?
    【解决方案2】:

    只需通过应用主题引用样式,此错误就会消失。这样做:

    style="@style/Theme.blue"
    

    【讨论】:

      【解决方案3】:

      不确定您的目标是什么:避免在 layout.xml 文件中提及 layout_widthlayout_height 对您来说很重要,还是您只是在寻找使用主题值的任何方式而没有指个人风格?

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

      layout_width="?attr/myCustomWidth"
      

      您在 CustomTheme 中的哪个位置定义了属性 myCustomWidth

      【讨论】:

      • 发送@marc1s。我想在 layout.xml 文件中避免 layout_width 和 Layout_height。
      • 是的,原因是所有按钮、文本字段或任何东西的定义都在样式定义中,而不是其中的一部分存在于某些值文件中
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-28
      • 2015-09-11
      • 2021-12-26
      • 2017-02-23
      • 2016-10-12
      • 1970-01-01
      相关资源
      最近更新 更多