如何正确使用Material主题?

How to correctly use Material theme?

我正在使用 minSdkVersion=21 开发应用程序。我不想支持 21 以下的旧 API。

Project structure > Dependecies 中,我仍然可以看到附加的 v7 支持库。这背后的原因是什么?

Material 主题应用到 API 21 设备的正确方法是什么,因为我不断因 Coordinator layout 膨胀而出错,或者它告诉我使用来自 Theme.AppCompat 而不是 android:Theme.Material.Light.DarkActionBar.

(为了安全起见跳过了一些属性)

Manifest.xml

<application
    android:theme="@android:style/Theme.Material.Light.DarkActionBar">
    <activity
        android:name=".MainActivity"
        android:theme="@android:style/Theme.Material.Light.DarkActionBar">
    </activity>
</application>

values\styles.xml

<style name="AppTheme" parent="android:Theme.Material.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">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

v21\styles.xml

<resources>
<style name="AppTheme" parent="android:Theme.Material.Light.DarkActionBar">
   <!-- item tags here -->
</style>
</resources>

build.gradle

compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
    applicationId "com.app.karti.themetestv3"
    minSdkVersion 21
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}

现在,我在这里得到 2 个例外: 1. Error inflating class android.support.design.widget.CoordinatorLayout 2. You need to use a Theme.AppCompat theme (or descendant) with the design library.

如果有人能提供帮助,我会很高兴。谢谢。

PS:MainActivity class 扩展 Activity 而不是 AppCompatActivity

What is the reason behind this?

因为要么是您自己添加的,要么是您使用了添加它的模板。例如,IDE 附带的 Android Studio new-project 和 new-activity 向导模板都使用 appcompat-v7.

What is the correct way to apply Material theme to API 21 devices because I keep on getting errors due to inflating of Coordinator layout or it tells me to use theme from Theme.AppCompat instead of android:Theme.Material.Light.DarkActionBar.

您不能使用 CoordinatorLayout 或 Android 设计支持库中的任何内容,除非您还使用 appcompat-v7 和所有需要的东西(例如,更改主题,使用 AppCompatActivity).

那么,您的选择是:

  1. 避免使用 appcompat-v7,不要管 activity 之类的东西,但不要使用 CoordinatorLayout

  2. 使用appcompat-v7,或

  3. 避免 appcompat-v7,让你的 activity 和其他东西单独存在,并尝试 cross-port CoordinatorLayout 和你想使用的任何其他东西Android 设计支持库不使用 appcompat-v7

我还没有尝试 cross-porting CoordinatorLayout。 Cross-porting ActionBarDrawerToggle 很顺利。 Cross-porting Snackbar 看起来很痛苦,所以我使用了一个不绑定的开源的 appcompat-v7