基本工具栏使应用程序崩溃

Basic toolbar crashes app

我在 android 网站上创建了一个基本工具栏,但它崩溃了,因为它提供了一个代码,用于放入 onCreate 部分。到目前为止,该程序中唯一的小部件就是它,它因 .java 代码

而崩溃

home.java

import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.os.Bundle;

public class Home extends AppCompatActivity {

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

    Toolbar my_toolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(my_toolbar);
}
}

xml

 <android.support.v7.widget.Toolbar
    android:id="@+id/my_toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    android:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

确保您的 activity Home 主题没有 ActionBar。检查清单文件以找出正在使用的主题。

同时检查文件 styles.xml 并确保您的 activity 使用的主题没有 ActionBar。使用这样的东西:

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

在你的 styles.xml 中输入下面的代码..

<!-- 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="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

并在你的AndroidManifest.xml中写下如下主题

       <activity android:name=".Home"
        android:theme="@style/AppTheme.NoActionBar"></activity>