首页 > 解决方案 > 使用没有清单的主题 - 尽管声明了主题,但应用程序崩溃

问题描述

所以我的应用程序目前声明了两个主题:

<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.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="AppThemeNoBar" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

我希望我的第一个屏幕没有操作栏,然后其余的屏幕使用操作栏。我已经从 AndroidManifest 中删除了 Theme 声明,因为这会导致声明的主题覆盖我在我的活动 xml 布局中声明的内容。在这样一种情况下(打开此活动会使应用程序崩溃):

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.DictionaryActivity"
android:theme="@style/AppTheme">

我在 XML 中声明主题,但它仍然崩溃。onCreate 如下:

public class DictionaryActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dictionary);

标签: android

解决方案


我希望我的第一个屏幕没有操作栏

但在您的布局 XML 文件中,您使用:

android:theme="@style/AppTheme" //shoule be AppThemeNoBar

如果您想使用 java 代码应用主题,可以在onCreate()方法中执行以下操作:

super.onCreate(savedInstanceState);
setTheme(R.style.MyTheme); // (for Custom theme),must called before setContentView
this.setContentView(R.layout.myactivity);

推荐阅读