class AppCompatActivity 中的 getSupportActionBar 无法应用于 android.support。v7.widget.Toolbar

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

实际上我在将 Android 应用程序更改为 material 设计时遇到了问题。

我尝试调用 getSupportActionbar 但我总是收到错误

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

我的密码是

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);
}

在 getSupportActionBar(mToolbar) 处抛出错误。

工具栏在 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" />

如果有人能帮助我,那就太棒了

必须是 setSupportActionBar(mToolbar) 而不是 getSupportActionBar(mToolbar)

添加到下面的 activity xml 布局代码中:

<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"
    />

在你的activityonCreate

这样写:

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

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

希望对您有所帮助。

if(工具栏!=空) {

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

}

这对我也有用,我收到了一个空指针引用。非常感谢!