setSupportActionBar cannot be applied to android.support.v7.widget.Toolbar

a 夏天 提交于 2019-12-14 04:11:11

问题


On this new project, when setting a toolbar into the main activity java file, it gets the error on

"setSupportActionBar(mToolbar)" saying "getSupportActionBar() in AppCompatActivity cannot be applyed to (android.support.v7.widget.Toolbar)"

On similar questions, the answers was just to change from "import android.widget.Toolbar" to "import android.support.v7.widget.Toolbar" which is already set. The main activity xml is this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent"
    tools:context=".MainActivity">

    <include
        android:id="@+id/main_page_toolbar"
        layout="@layout/app_bar_layout"
        >
    </include>


</RelativeLayout>

The toolbar I'm trying to insert is:

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

</android.support.v7.widget.Toolbar>

And the main java file:

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

public class MainActivity extends AppCompatActivity {

    private Toolbar mToolbar;

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

        mToolbar =  findViewById(R.id.main_page_toolbar);
        getSupportActionBar(mToolbar);
        getSupportActionBar().setTitle("WhatsApp");
    }
}

Am I missing something? A compatibility set?


回答1:


Looks like it's a typo, and you're calling getSupportActionBar() (with a g) instead of setSupportActionBar().




回答2:


You need to use setSupportActionBar() to configure toolbar in the activity:

public class MainActivity extends AppCompatActivity {

    private Toolbar mToolbar;

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

        mToolbar =  findViewById(R.id.main_page_toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setTitle("WhatsApp");
    }
}


来源:https://stackoverflow.com/questions/53962841/setsupportactionbar-cannot-be-applied-to-android-support-v7-widget-toolbar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!