我为按钮栏创建了一个自定义主题,在每个按钮上使用ButtonBarStyle,在布局上使用ButtonBarButtonStyle。
它工作正常,但我想更改按钮的文本颜色,但它仍然采用默认颜色(@android:color/primary_text_holo_light)
我的代码是:
<style name="ButtonBarTheme" parent="AppTheme">
<item name="buttonBarStyle">?android:attr/buttonBarStyle</item>
<item name="buttonBarButtonStyle">?android:attr/buttonBarButtonStyle</item>
<item name="android:textColor">#ffffff</item>
</style>
对于布局:
<LinearLayout
style="?android:attr/buttonBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#0090cc"
android:orientation="horizontal" >
<Button
android:id="@+id/bar_button1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
style="@style/ButtonBarStyleButton"
android:text="Button 1" />
<Button
android:id="@+id/bar_button2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
style="?android:attr/buttonBarButtonStyle"
android:text="Button 2" />
</LinearLayout>
apptheme有父appbasetheme,它有父android:theme.holo.light.darkactionbar。
我需要做什么来更改按钮的文本颜色?
编辑:
我试着在每个元素上应用颜色,但我想通过重写样式文件中的颜色来更改它(将所有设计属性放在一个位置,类似于css)。
另外,我试图创建一个具有属性的样式?安卓系统:attr/buttonbarstyle”
<style name="ButtonBarStyleButtonBase">
<item name="buttonBarButtonStyle">?android:attr/buttonBarButtonStyle</item>
</style>
<style name="ButtonBarStyleButton" parent="ButtonBarStyleButtonBase">
<item name="android:textColor">#ffFFff</item>
</style>
但是它的行为很奇怪:颜色被更新,但是父样式的属性不可见。
最佳答案
在回答这个问题之前,我想说我不完全理解什么是按钮栏。android开发人员文档除了为它们定义一些样式属性之外,似乎没有提到它们,因此我不确定它们如何映射到实际的视图/小部件。
我相信你忽略了风格和主题之间的区别。样式应用于视图以定义其属性。主题应用于整个应用程序或单个活动,并提供为应用主题的应用程序/活动中显示的视图定义默认样式的功能(除其他外)。
不过,更重要的是,buttonBarStyle和buttonBarButtonStyle等属性将仅由活动用于解析按钮栏和按钮栏中的按钮的默认样式。因为这些属性只由活动解析,所以如果直接应用于视图,它们将被忽略。
因此,如果要使用主题应用样式,则需要创建扩展所需基本样式的新样式定义,然后将该自定义样式指定回主题定义中的相应视图样式属性。
<style name="CustomButtonStyle" parent="@android:attr/buttonStyle">
<item name="android:textColor">#ffffff</item>
</style>
<style name="AppTheme" parent="@android:style/Theme.Holo.Light.DarkActionBar">
<item name="buttonStyle">@style/CustomButtonStyle</item>
</style>
<application
...
android:theme="@style/AppTheme" >
现在,所有没有显式样式属性的按钮都将显示为白色文本。
但是,对于希望显示具有ButtonBar样式的按钮的特殊情况,应注意ButtonBar样式不会自动应用于按钮。必须手动定义要以该样式显示的按钮。因此,上面的示例现在看起来更像这样:
<style name="CustomButtonBarStyle" parent="@android:attr/buttonBarStyle">
<item name="android:textColor">#ffffff</item>
</style>
<style name="AppTheme" parent="@android:style/Theme.Holo.Light.DarkActionBar">
<item name="buttonBarStyle">@style/CustomButtonBarStyle</item>
</style>
<application
...
android:theme="@style/AppTheme" >
现在应用为当前主题定义的ButtonBar样式:
<Button
...
style="?android:attr/buttonBarStyle"/>
请注意,这将应用为当前主题定义的ButtonBar样式(除非被活动覆盖,否则在整个应用程序中都是相同的)。还要注意,由于您引用的是为当前主题定义的样式,因此它允许您根据所需的资源限定符以不同的方式定义当前主题,而无需更改布局代码。