【问题标题】:getSupportActionBar in class AppCompatActivity cannot be applied to android.support.v7.widget.Toolbar类 AppCompatActivity 中的 getSupportActionBar 无法应用于 android.support.v7.widget.Toolbar
【发布时间】:2015-10-20 03:08:00
【问题描述】:

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

我尝试调用 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)

标签: android android-actionbar material-design android-appcompat


【解决方案1】:

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

【讨论】:

  • 难以置信,我一直在寻找错误的时间 -.- 非常感谢
  • Ctrl+v 时一定要小心 :)
【解决方案2】:

在下面添加到您的活动 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"
    />

在您的活动中onCreate

这样写:

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

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

希望对您有所帮助。

【讨论】:

    【解决方案3】:

    如果(工具栏!= null) {

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

    }

    这也对我有用,我收到了一个空指针引用。所以谢谢你!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      • 2014-12-21
      • 1970-01-01
      • 2015-01-18
      • 1970-01-01
      • 2017-09-03
      相关资源
      最近更新 更多