Android样式继承

4

以下是要翻译的内容:

问题在这里:在我的Styles.xml文件中,我有一个通用样式和一个继承它的样式,如下所示:

<resources>

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="AppTheme.NoActionBar" parent="@style/AppTheme">
    <item name="colorPrimary">#0acf66</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowNoTitle">true</item>
</style>

当我应用第二个主题(AppTheme.NoActionBar)时,它继承了颜色,但操作栏仍然存在。如果我将第二个样式的父级更改为Theme.AppCompat.NoActionBar,则可以解决问题,但颜色完全不同。我该如何解决?

1个回答

8
这是一个关于样式/主题继承的问题。有两种方式可以从样式中继承属性。
1. 通过点表示法(隐式):
<style name="Theme.AppCompat.NoActionBar.Custom">
  // the parent will be Theme.AppCompat.NoActionBar
</style>

2.通过父标签(显式)

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
   //the parent is Theme.AppCompat.Light.DarkActionBar
</style>

永远记住一件事,显式继承优先于隐式继承。

因此在您的情况下

<style name="AppTheme.NoActionBar" parent="@style/AppTheme">
    // your parent is AppTheme, and new style is AppThem.NoActionBar,
       but it doesn't inherit from an actual NoActionBar style.
</style>

为了使用“无操作栏”主题,您确实需要继承具有该属性的样式。因此,您可以创建另一个从Theme.AppCompat.NoActionBar继承的AppTheme.NoActionBar
要更好地了解主题/样式,请查看这个关于样式和主题的精彩Google I/O 2016链接。

谢谢回复。我只是想避免在两个主题中重复使用像<item name="colorPrimary">#0acf66</item>这样的项目。有没有办法做到这一点,同时在第二个主题中隐藏操作栏? - Matheus Neves
据我所知,没有。但通常的做法是使用相同属性的两个主题,一个带有操作栏,另一个不带。 - danypata

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