Search code examples
androidtoolbarandroid-toolbarandroidx

Applying toolbar in androidx


All similar questions are on older versions.Hence i had no option but to ask this. My imports:

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

The class MainActivity extends AppCompactActivity, id for the toolbar is the same and toolbar is initialized.Also the action bar in style is set to NoActionBar already. The implementation is as below:

toolbar= findViewById(R.id.toolbar1);
getSupportActionBar(toolbar);

Error: getSupportActionBar() in AppCompactActivity cannot be applied to (androidx.appcompat.app.AppCompatActivity)

toolbar defined in activity_main.xml as

<include layout="@layout/toolbar"
            android:id="@+id/toolbar1"/>

Code for toolbar layout resource file:

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@color/colorPrimary"
    android:elevation="4dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <ImageButton
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/HomeBtn"
        android:background="@mipmap/home"
        android:contentDescription="@string/homebtn" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Random text"
        android:textAlignment="center"
        android:padding="5dp"/>
</androidx.appcompat.widget.Toolbar>

How can i make my toolbar work?


Solution

  • You're using getSupportActionBar. You should be using setSupportActionBar:

    setSupportActionBar(toolbar);