如何使用appcompat设置视图样式

ano*_*ous 5 android android-appcompat

当主题从Theme.AppCompat.Light.DarkActionBar扩展时,如何在整个应用程序中设置textview,edittexts的样式?

这不起作用,

<style name="myTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
        <item name="android:textViewStyle">@style/myTextViewStyle</item>
        <item name="textViewStyle">@style/myTextViewStyle</item>
</style>

<style name="myTextViewStyle" parent="android:Widget.TextView">
    <item name="android:layout_marginLeft">5dp</item>
    <item name="android:layout_marginRight">5dp</item>
    <item name="android:layout_marginTop">5dp</item>
    <item name="android:layout_marginBottom">5dp</item>
    <item name="android:textColor">@android:color/black</item>
</style>
Run Code Online (Sandbox Code Playgroud)

Eug*_*nec 0

<!-- Maintain *theme* naming convention Theme.ThemeName. It helps with organization. -->
<style name="Theme.MyApp" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:textViewStyle">@style/Widget.MyApp.TextView</item>
    <!-- AppCompat does not provide its own variant of textViewStyle attribute. -->
    <item name="editTextStyle">@style/Widget.MyApp.EditText</item>
</style>

<!-- Maintain *style* naming convention Widget.ThemeName.WidgetName. -->
<!-- TextView is a simple widget, use the parent provided by platform. -->
<style name="Widget.MyApp.TextView" parent="android:Widget.TextView">
    <!-- ... -->
</style>

<!-- EditText parent is provided by AppCompat. -->
<style name="Widget.MyApp.EditText" parent="Widget.AppCompat.EditText">
    <!-- ... -->
</style>
Run Code Online (Sandbox Code Playgroud)

只要您的应用程序或活动已android:theme="@style/Theme.MyApp在清单中定义,它就可以工作。

几点注意事项:

  • 如果您想为另一个小部件提供默认样式,请像这样尝试:
    • widgetNameStyle在您的主题中覆盖。
    • 如果该属性不存在,请在其前面添加前缀android:
    • 如果这不起作用,那么它是一个自定义小部件,这超出了本文的范围。
    • android:如果存在 -prefixed 和 unprefixed 变体,请不要覆盖它们!只有一个有效。
    • 无前缀属性来自 AppCompat,使用 AppCompat 样式作为父属性。
    • 前缀属性来自 Android SDK,使用平台样式作为父级 (TextViewProgressBar)。
  • 不要混合主题和风格。主题在上下文范围内应用于整个视图层次结构(android:theme属性)。样式用于小部件(style属性)。