问题
I'm trying to implement an activity that has the Material Design tinted title bar.
My standard style is:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
</style>
My v21 style is:
<style name="AppTheme" parent=" -see rest of this post- ">
<item name="android:colorPrimary">@color/primary</item>
<item name="android:colorPrimaryDark">@color/primary_dark</item>
<item name="android:colorAccent">@color/accent</item>
</style>
and the results I get are:
API 18:
MyActivity extends AppCompatActivity
-- Black title bar, this is good enough.
MyActivity extends Activity:
-- No title bar.
API 21:
MyActivity extends Activity, parent="android:Theme.Material.Light"
-- Perfect green tinting of status bar and title bar.
MyActivity extends AppCompatActivity, parent="android:Theme.Material.Light"
-- Crashes with: You need to use a Theme.AppCompat theme (or descendant) with this activity.
MyActivity extends AppCompatActivity, parent="Theme.AppCompat.Light"
-- Status bar is correctly green tinted. Title bar has no background colour.
MyActivity extends AppCompatActivity, parent="Theme.AppCompat.Light.DarkActionBar"
-- Status bar is correctly green tinted. Title bar has black background colour.
How do I get the coloured title bar in Lollipop and an acceptable one pre-Lollipop? I know with extra work I can have a coloured pre-lollipop title bar, but that is not needed at this time.
回答1:
You should be using the non-android namespaced properties with the support library:
<style name="AppTheme" parent="Theme.AppCompat.Light">
<item name="colorPrimary">@color/primary</item>
<item name="colorPrimaryDark">@color/primary_dark</item>
<item name="colorAccent">@color/accent</item>
</style>
No v21 version required. This will give you consistent behavior back to API level 7
回答2:
If you are using AppCompat, then all of the material color palette attributes (such as colorPrimary
) are available to all API levels, so you can write a single theme:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/primary</item>
<item name="colorPrimaryDark">@color/primary_dark</item>
<item name="colorAccent">@color/accent</item>
</style>
And use AppCompatActivity for all of your activities as per the Consistent Design with AppCompat DevByte. This will give you an action bar with colorPrimary
on all API7+ devices, a status bar of colorPrimaryDark
on API21+ devices (older devices do not support colored status bars), and light text on your action bar (use Theme.AppCompat.Light
if you want dark text on your action bar).
来源:https://stackoverflow.com/questions/30089378/maintaining-backward-compatibility-with-material-design