setSupportActionBar cannot be applied to android.s

2019-09-20 20:30发布

问题:

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