【问题标题】:Android apply a theme on a custom itemAndroid 在自定义项目上应用主题
【发布时间】:2012-04-24 09:43:53
【问题描述】:

我可以声明一个主题和一个特定的按钮设计:

<style name="MyTheme" parent="android:style/Theme.Black">
  <item name="android:buttonStyle">@style/Button.b1</item>
</style>

<style name="Button.b1" parent="android:style/Widget.Button">
    <item name="android:textColor">#000000</item>
</style>

问题是这种样式适用于所有按钮。我想用他自己的风格声明一个特定的按钮,改变每个主题独立于其他按钮(类似于“保存”按钮)。任何的想法?


我尝试了以下方法:

<style name="Button.MyButton" parent="android:style/Widget.Button">
  <item name="android:background">@drawable/shape</item>
</style>

 <style name ="Button.MyButton.Theme1">
     <item name="android:textColor">#000000</item>
  </style>

 <style name ="Button.MyButton.Theme2">
     <item name="android:textColor">#FFFFFF</item>
  </style>

 <Button
     android:id="@+id/save_button" 
     android:layout_width="0px" 
     style="@style/Button.MyButton"
     android:layout_weight="1"
     android:layout_height="wrap_content"
     android:text="@string/save"/>

现在按钮独立于主题,但它也应该应用我上面声明的样式属性。目前它只应用在 MyButton 范围中声明的属性,而不是在 MyButton.Theme1 或 MyButton.Theme2 中声明的属性。

【问题讨论】:

标签: android styles themes


【解决方案1】:

如果您的主题MyTheme 仅用于定义按钮样式,请将其删除;还从按钮中删除 parent 属性:

<style name="Button.b1">
    <item name="android:textColor">#000000</item>
</style>

然后在布局中,只为那些你需要的按钮使用样式,如下所示:

 <Button
         android:id="@+id/btn_custom"
         style="@style/Button.b1"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content" >
 </Button>

【讨论】:

  • Mytheme 比这里大,但它应该包含一个特定的样式元素,其中包含仅用于保存按钮的信息。如果我更改主题,保存按钮也应该以他自己的方式更改。
  • 这并不意味着您必须在 MyTheme 中设置“保存”按钮样式。你是如何改变主题的?以编程方式?
  • 因为它应该在运行时,我想我会在每个活动开始时以编程方式执行此操作。
  • 那么您可能还应该同时应用“保存”按钮特殊样式。(也就是说,如果您找到一种以编程方式应用样式的方法,也许这个 (blog.infidian.com/2008/05/02/…) 也很有用)
【解决方案2】:

您可以从您的styles.xml 中删除MyTheme 声明,并在您选择的按钮的android:style 属性中轻松设置@style/Button.b1 :)

编辑:我想我终于得到了你想要的东西。我自己没有尝试过,但它应该可以工作:

<!-- Declare your themes here -->
<style name="Theme1" parent="android:style/Theme.Black"></style>
<style name="Theme2" parent="android:style/Theme.Black"></style>

<!-- Declare your "abstract" Button style -->
<style name="MyButton" parent="android:style/Widget.Button">
  <item name="android:background">@drawable/shape</item>
</style>

<!-- Override MyButton style for Theme1 -->
<style name ="Theme1.MyButton" parent="@style/MyButton">
  <item name="android:textColor">#000000</item>
</style>

<!-- Override MyButton style for Theme2 -->
<style name ="Theme2.MyButton" parent="@style/MyButton">
  <item name="android:textColor">#FFFFFF</item>
</style>

【讨论】:

    【解决方案3】:

    您应该仅将Button.b1 样式直接用于您希望以这种方式设置样式的那些按钮。使用这些按钮的android:style 属性:

    android:style="Button.b1"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多