java.lang.ClassCastException: android.widget.LinearLayout 无法转换为 android.support.v7.widget.Toolbar

java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.support.v7.widget.Toolbar

我试图按照这里的示例向工具栏添加阴影

我的工具栏在 activity

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

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

这是我添加工具栏的 xml 文件

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">

<android.support.v7.widget.Toolbar            
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/primaryColor"
android:paddingTop="@dimen/app_bar_top_padding"
app:popupTheme="@style/ThemeOverlay.AppCompat.Dark"
app:theme="@style/MyCustomToolBarTheme">

</android.support.v7.widget.Toolbar>
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- **** Place Your Content Here **** -->

    <View
        android:layout_width="match_parent"
        android:layout_height="5dp"
        android:background="@drawable/shadow" />
</FrameLayout>
</LinearLayout>

我在 logcat 中得到了这个 java.lang.ClassCastException: android.widget.LinearLayout 无法转换为 android.support.v7.widget.Toolbar

我怎样才能摆脱这个错误?

在您的工具栏中添加 id 属性 并检查您是否有另一个具有相同 id 的元素。

<android.support.v7.widget.Toolbar 
   android:id="@+id/toolbar"
   .....
/>

也比较好:

 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null)
        setSupportActionBar(toolbar);