Search code examples
androidtoolbarandroid-toolbarandroid-appcompatandroidx

How to set NavigationIcon on Toolbar ("java.lang.ClassCastException" error)


I want to have a back button on my toolBar, but I am stuck with this error:

java.lang.ClassCastException: androidx.appcompat.widget.Toolbar cannot be cast to android.widget.Toolbar

This is my xml file:

    <androidx.appcompat.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/toolbar"
        android:background="@color/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="20dp"
            android:text="InstaPF for Instagram"
            android:textColor="@color/Black"
            android:id="@+id/Textbar"/>


    </androidx.appcompat.widget.Toolbar>

Code:

        Toolbar mToolbar = (android.widget.Toolbar) findViewById(R.id.toolbar);

        mToolbar.setNavigationIcon(R.drawable.ic_menu_share);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                finish();
            }
        });

Does somebody also know to icon of the back button. I have this set just for testing: R.drawable.ic_menu_share.

Thanks


Solution

  • You have to import in your code:

    import androidx.appcompat.widget.Toolbar;
    

    instead of android.widget.Toolbar

    Also remove the casting:

    //Toolbar mToolbar = (android.widget.Toolbar) findViewById(R.id.toolbar);
    Toolbar mToolbar = findViewById(R.id.toolbar);