Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...