简体   繁体   中英

Can't apply themes and styles in Android

I've been searching the solution for hours: how to apply a simple theme or style to an application, an activity or just a view? It seems super easy but my styles always get ignored.

Here is the code in style.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="master" parent ="@android:style/Theme.NoTitleBar">
        <item name="android:typeface">serif</item>
        <item name="android:textColor">#8b8378</item>
    </style>
</resources>

and here is the code in AndroidManifest.xml:

<application android:icon="@drawable/icon" 
        android:label="@string/app_name"
        android:theme="@style/master">

and code in a ListView

<ListView android:layout_height="wrap_content" 
style="@style/master"
android:id="@+id/list" 
android:layout_width="fill_parent">
</ListView>

NOTHING ever happens . Font style, color all remain the default. Only by declare the attributes explicitly like

<TextView android:gravity="center" android:typeface="serif" android:textColor="#8b7d6b" android:textAppearance="?android:attr/textAppearanceSmall" android:id="@+id/text_intro" android:layout_height="wrap_content" android:text="@string/welcome_text" android:layout_width="wrap_content" android:padding="20sp" android:layout_weight="0"></TextView>

will work. I know eclipse doesn't support preview of theme and style, but they don't work on emulator as well.

Help please! I can't believe I have been stuck with this tiny issue for a week... Thank you in advance!

There are a few things about Android styles and resources at work here.

Android styles are an extremely general facility, and the result is that some configurations are possible but invalid and will be ignored. You've run across a few. :)

When applied to a view, a style will be equivalent to setting those same attributes on that view. Styles do not cascade to child views. typeface and textColor aren't valid on a ListView, so they are ignored. They also aren't going to work on a theme that way, since themes provide default styles for different kinds of views. (Why are invalid attributes silently ignored instead of generating an error? Because as new attributes are added in later platform revisions, older devices should ignore extra attributes that they don't know how to parse for compatibility.)

The best way to accomplish what you're trying to do is likely to be:

  • Create a style for TextViews. (This shouldn't have a parent that is a theme like your pasted code does.)
  • Apply that style to the TextView in your list item layout using the style= syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM