android 工具栏不再有效

android toolbar no longer works

所以我的朋友 "helped" 我对我的程序稍微了解了一下,只是他的帮助带来的问题多于实际帮助。我曾经在我的一个活动中有一个工具栏,当其余代码工作时,如果工具栏存在,程序总是会停止。没有任何错误。如何解决这个问题?

代码:

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;

public class ProjectCreateScreen extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.secondary_layout1);

    Toolbar toolbar = (Toolbar) findViewById(R.id.AwesomeBar);
    setSupportActionBar(toolbar);

    }
}

xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rl">

    <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?android:attr/actionBarSize"
        android:id="@+id/AwesomeBar"
        android:background="@color/custom_white">
    </android.support.v7.widget.Toolbar>

</RelativeLayout>

代码比我在这里发布的多很多,但我删除了它,因为除了这部分以外的所有东西都有效。

如果错误如您上面所评论的那样:

Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead

这意味着您没有禁用 activity 及其主题提供的 Android 的默认操作栏。进入您的 styles.xml 文件并找到您 activity 正在使用的主题(如果所有活动都使用相同的主题,则应用程序正在使用)并执行以下操作(示例):

<style name="AppThemeToolbar" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowActionBar">false</item>
     ...
     ...
</style>

android:windowActionBar 设置为 false 将禁用默认操作栏,您使用自定义 toolbar/actionbar 的活动现在将不再崩溃。