使用Android Studio在活动中实现工具栏的正确方法

我在向应用程序添加工具栏时遇到问题。我从一个空的活动开始。使用本教程https://developer.android.com/training/appbar/setting-up和本教程https://m.youtube.com/watch?v=DMkzIOLppf4

但是,尽管implementation 'com.android.support:appcompat-v7:28.0.0' 被添加到build.gradle(Module:app)中的依赖项,使用支持库似乎不起作用,因为出现以下错误:

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

我已经发现这可能是由于启用了androidx而引起的,实际上,我发现了

android.useAndroidX=true
android.enableJetifier=true
在gradle.properties中的

。但是,将两者都设置为false会给我以下错误:

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.

但是,老实说,我不知道该如何处理该错误消息...

您能告诉我添加工具栏的正确方法是什么。如果启用了androidx,您能指出我的教程吗?反之,如果是通过android.support.v7.widget,我该怎么做才能使其正常工作?

谢谢!

weiyi961013 回答:使用Android Studio在活动中实现工具栏的正确方法

我想我找到了解决方案。 无需实施com.android.support:appcompat-v7:28.0.0。改为使用

androidx.appcompat.widget.Toolbar

在Java文件中,您需要添加

import androidx.appcompat.widget.Toolbar;

并使用设置工具栏

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

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

但是,如果有经验的人能够验证此解决方案的正确性,我将感到非常高兴。

本文链接:https://www.f2er.com/3129837.html

大家都在问