Search code examples
androidandroid-studioandroid-toolbar

Correct way to implement a toolbar in activity using android studio


I have a problem adding a toolbar to my app. I started with an empty activity. Using this tutorial https://developer.android.com/training/appbar/setting-up and this tutorial https://m.youtube.com/watch?v=DMkzIOLppf4.

However, although implementation 'com.android.support:appcompat-v7:28.0.0' is added to the dependencies in build.gradle (Module:app), using the support library does not seem to work as I get following error:

package android.support.v7.widget does not exist
import android.support.v7.widget.Toolbar;

I already found that this might be due to enabled androidx and indeed, I found

android.useAndroidX=true
android.enableJetifier=true

in gradle.properties. However, setting both to false gives me the following error:

ERROR: Manifest merger failed : Attribute application@appComponentFactory value=(androidx.core.app.CoreComponentFactory) from [androidx.core:core:1.0.1] AndroidManifest.xml:22:18-86 is also present at [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91 value=(android.support.v4.app.CoreComponentFactory). Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:5:5-24:19 to override.

But to be honest, I do not know what to do with that error message...

Could you tell me what's the correct way to add a toolbar. And in case it is with androidx enabled, could you point me to tutorial? And the other way around, in case it is via android.support.v7.widget, what do I have to do to make it work?

Thank you!


Solution

  • I guess I found the solution. It is not necessary to implementcom.android.support:appcompat-v7:28.0.0. Instead use

    androidx.appcompat.widget.Toolbar
    

    In the java-File you need to add

    import androidx.appcompat.widget.Toolbar;
    

    and set up the toolbar with

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
    }
    

    However, I would be glad if someone more experienced could verify this solution to be correct.