无法应用AppCompatActivity中的setSupportActionBar(androidx.appcompat.widget.Toolbar)

时间:2019-07-02 08:00:07

标签: android android-appcompat androidx

在Android Studio上工作时,无法在Java编译器中转换显示不兼容类型的Android小部件工具栏的错误。

    Toolbar toolbar = (Toolbar)findViewById(R.id.toolBar);
    toolbar.setTitle("GPS PRESENCE SYSTEM");
    setSupportActionBar(toolbar);
  

错误:类型不兼容:android.widget.Toolbar无法转换   到androidx.appcompat.widget.Toolbar

9 个答案:

答案 0 :(得分:1)

此错误是因为您的工具栏是使用android.widget.Toolbar创建的。 但是您正在使用androidX。 这也是同一种错误。 java.lang.ClassCastException:androidx.appcompat.widget.Toolbar无法转换为android.widget.Toolbar

要解决这种情况,您可以将它们添加到MainActivity.java文件中的行中(以导入)。

import androidx.appcompat.app.AppCompatActivity;

import androidx.appcompat.widget.Toolbar;

请确保删除或删除此android.widget.Toolbar。 然后再次检查是否有这样的错误。因为有时您可能需要导入更多。

答案 1 :(得分:1)

AndroidX是经过改进的新支持库

 import androidx.appcompat.widget.Toolbar;

您可以在这里here

中查看更多信息

Androidx的工具栏旨在向后兼容,同时

android.widget.Toolbar

是当前平台类型

答案 2 :(得分:0)

将活动工具栏导入更改为:

导入android.support.v7.widget.Toolbar;

答案 3 :(得分:0)

您同时使用androidx和Android。那抛出一个错误。使用androidx或android appcompat。

答案 4 :(得分:0)

尝试替换为:

import android.widget.Toolbar;

与此:

import androidx.appcompat.widget.Toolbar;

顺便说一句,如果您使用的是androidx。运行其迁移过程。 以后将不再支持android支持库。 您可以在这里阅读有关内容:

AndroidX Migrating to AndroidX

答案 5 :(得分:0)

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

    Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
    setSupportActionBar(toolbar); //No Problerm

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
  

我们必须导入androidx.appcompat.widget.Toolbar;   不要导入android.widget.Toolbar;

答案 6 :(得分:0)

您可以调用ActivityCompat#requireViewById,该方法可以忽略强制类型转换并返回一个@NonNull Toolbar引用:

Toolbar toolbar = ActivityCompat.requireViewById(this, R.id.toolbar);
setSupportActionBar(toolbar);

可以在AppCompatActivity#getSupportActionBar返回的@Nullable ActionBar参考上设置标题:

ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
    actionBar.setTitle("GPS PRESENCE SYSTEM");
}

答案 7 :(得分:0)

只需删除

import android.widget.Toolbar;

并添加

import androidx.appcompat.widget.Toolbar;

答案 8 :(得分:0)

据其他人报道

import android.widget.Toolbar

正在制造问题。

替换为

import androidx.appcompat.widget.Toolbar

主要是根据 android 的建议,我们选择了该工具,而没有注意到 android 或 androidx 的可靠性。 这会导致此错误。

相关问题