Stevetro
Stevetro

Reputation: 1963

getSupportActionBar in class AppCompatActivity cannot be applied to android.support.v7.widget.Toolbar

actually i've got a problem with changing my Android App to material design.

I try to call getSupportActionbar but i always receive the error

getSupportActionBar in class AppCompatActivity cannot be applied to android.support.v7.widget.Toolbar

My Code is

import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

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

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

    getSupportActionBar(mToolbar);

    getSupportActionBar().setDisplayShowHomeEnabled(true);
}

The error is thrown at getSupportActionBar(mToolbar).

The Toolbar is declared in toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
local:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

Would be aweseome of someone of you can help me

Upvotes: 0

Views: 6838

Answers (3)

JavaCouldBeMe
JavaCouldBeMe

Reputation: 11

if (toolbar != null) {

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true); // or other

}

This also worked for me, I was receiving a null pointer reference. So thank you!

Upvotes: 0

user5400869
user5400869

Reputation:

Add to your activity xml layout code below:

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

In your activity onCreate

Write this:

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

        if (toolbar != null)
        {
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setElevation(0); // or other
        }

Hope this help.

Upvotes: 2

aiwiguna
aiwiguna

Reputation: 2922

it must be setSupportActionBar(mToolbar) not getSupportActionBar(mToolbar)

Upvotes: 8

Related Questions