RelativeLayout cannot be added to android.support.v7.widget.Toolbar

I want to add a shadow to the ToolBar, and I use the following link: Toolbar Shadow

but the running application will show me this error in LogCat:

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

Toolbar Code:

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="200dp"> <android.support.v7.widget.Toolbar android:layout_width="match_parent" android:layout_height="200dp" app:popupTheme="@style/ThemeOverlay.AppCompat.Dark" app:theme="@style/MyCustomToolbarTheme" android:background="@drawable/main_header"> </android.support.v7.widget.Toolbar> 

MainActivity XML:

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <include android:id="@+id/app_bar" layout="@layout/app_bar_main"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/app_bar" android:text="ytkbhjk"/> 

MainActivity Java:

 public class MainActivity extends ActionBarActivity { private Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.app_bar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowHomeEnabled(true); } 

Please help me

+6
source share
4 answers

You will need to make another XML file containing your toolbar: The name of this xml is the toolbar

 <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorPrimary"/> 

Now change your relative include tag like this

 <include layout="@layout/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content"/> 

And in your activity do something like this:

 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
+3
source

Where you use <include /> in your MainActivity XML file, you should not put android:id="@+id/app_bar" , but instead in the <android.support.v7.widget.Toolbar /> .

+2
source

I deleted relativeLayout , but just used android.support.v7.widget.Toolbar . And working.

+1
source

Try downloading the android_m2repository_r29.zip repository from https://developer.xamarin.com/guides/android/troubleshooting/resolving-library-installation-errors/ with the instructions given in the same.

0
source

Source: https://habr.com/ru/post/984955/


All Articles