[英]java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.support.v7.widget.Toolbar
I was trying to add a shadow to the toolbar following this example over here https://stackoverflow.com/a/26904102/4273056 我试图在此示例后面的工具栏中添加阴影https://stackoverflow.com/a/26904102/4273056
My toolbar in activity 活动中的工具栏
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
This is the xml file where I added the 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>
I get this in the logcat java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.support.v7.widget.Toolbar 我在logcat中得到了这个java.lang.ClassCastException:android.widget.LinearLayout无法强制转换为android.support.v7.widget.Toolbar
How can I get rid of this error? 我怎样才能摆脱这个错误?
Add the id attribute in your Toolbar and check if you have another element with the same id. 在工具栏中添加id属性 ,并检查是否有另一个具有相同ID的元素。
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
.....
/>
Also it is better: 它也更好:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null)
setSupportActionBar(toolbar);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.