android material 使用 AppCompatActivity 设计

android material design with AppCompatActivity

为了支持 API 19 及以下版本,我让我的活动扩展了 AppCompatActivity。 我尝试为 v21 parent="android:Theme.Material" 设置以下父主题 当我尝试 运行 我的应用程序时,它给出了一个异常并告诉我使用 Activity 而不是 AppCompatActivity.

这是否意味着我必须为 API 21 及以上创建扩展 Activity 的新活动才能获得 material 设计?或者有更好的方法吗?

这就是我设置 themes.xml 文件以支持 material 设计的方式:

<resources>

<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="windowActionBar">false</item>
    <item name="android:windowNoTitle">true</item>
</style>

</resources>

现在,在您的 activity 中,您可以像往常一样扩展 AppCompatActivity,您将获得您想要的外观!祝你好运!

AppCompatActivity 需要 AppCompat 主题。 使用不同的主题,比如 android:Theme.Material 你会得到

java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity

只需在您的 styles.xml 文件中定义一个主题:

<style name="AppTheme" parent="Theme.AppCompat">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>

    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

使用 AppCompat 主题,您也可以在 API <21.

的设备中使用 Material 设计

android:Theme.Material 只能与 API >= 21 一起使用。