使用主题更改 Android 样式

Changing Android styles by using theme

我有一个应用程序有一些不同 Activities。不同的活动具有不同样式的按钮、文本等...我已将所有组件设置为具有基于它们 location/Activity 的各种样式。 (例如 style="@style/MainMenuActionBarTitlestyle="@style/MainMenuActionBarTagLine)。这些样式设置 backgroundDrawableMipMapColor)、textColor 等...

该应用程序将提供一些主题包,这些主题包会在整个应用程序中更改这些不同组件的颜色,我希望有一种方法可以让 Styles 具有相同的名称,但基于不同的值应用程序的 Theme。这样我就可以在 Activity 加载到用户选择的任何主题时更改 Theme

有一些关于如何使用主题更改标准小部件外观的有用信息 here,但这会改变标准非样式化小部件的外观。

有没有办法使用主题来完成这个,或者这完全是错误的方向?有better/easier条路线吗?

编辑: 经过更多的研究和更多的尝试,我意识到我想做的离我能完成的事情不远了。我想要做的是在设置 ActivityTheme 时实际更改组件 Styles

我发现的一个解决方案是使用 attributes,其中 Theme 可以指向不同的 Styles

attrs.xml

<resources>
   <!-- Attributes referencing whatever style the theme needs to set up. -->
   <attr name="main_menu_button_style_play" format="reference" />
</resources>

themes.xml

<resources>
   <!-- Base application theme. -->
   <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
       <!-- App specific attributes -->
       <item name="@attr/main_menu_button_style_play">@style/MainMenu.Button.Play</item>
   </style>

   <!-- Blue application theme. -->
   <style name="AppTheme.Blue" parent="AppTheme">
      <!-- App specific attributes -->
      <item name="@attr/main_menu_button_style_play">@style/MainMenu.Button.Play.Blue</item>
   </style>
</resources>

styles.xml

<style name="MainMenu.Button.Play">
    <item name="android:background">#f76d3c</item>
    <item name="android:text">PLAY</item>
</style>

<style name="MainMenu.Button.Play.Blue">
    <item name="android:background">#2ca8c2</item>
</style>

activity.xml

<Button android:id="@+id/main_play_button"
        style="?attr/main_menu_button_style_play"/>

这非常有效,让我可以在 Activity.onCreate() 方法中设置 Theme

这个解决方案唯一烦人的问题是 Android Studio 抱怨 Button 缺少 layout_widthlayout_height,即使它们已定义在 Style。我猜它不会通过选择的 Theme.

来跟踪属性引用

我最终使用的另一种方法是更多地使用属性。为我想在主题之间更改的所有属性值创建属性。因此,我使用了 main_menu_button_play_background,而不是定义样式引用的 main_menu_button_style_play。这种方法与简单地指定样式的工作量相同,因为主题可以继承,但 IDE 理解它。