android.widget.Toolbar 和 android.support.v7.widget.Toolbar 有什么区别?

What's the difference between android.widget.Toolbar and android.support.v7.widget.Toolbar?

有人可以向我解释一下它们之间的区别以及为什么它们不能互换吗?

导入 android.widget.Toolbar 会导致编译错误,而导入 android.support.v7.widget.Toolbar 可以正常工作。

这两个导入有什么区别?

import android.widget.Toolbar;

...

Toolbar toolbar = findViewById(R.id.app_bar);

setSupportActionBar(toolbar);

import android.support.v7.widget.Toolbar;

...

Toolbar toolbar = findViewById(R.id.app_bar);

setSupportActionBar(toolbar);

当你看到v4 Support Libraries时就知道它是android低API级别(向后兼容)的旧设备的支持库。

These libraries include the largest set of APIs compared to the other libraries, including support for application components, user interface features, accessibility, data handling, network connectivity, and programming utilities.

你可以检查所有的支持库here

注意 - 您也可以使用 AndroidX ,它是新的和改进的支持库。

AndroidX is a major improvement to the original Android Support Library.

支持库(现在 )是为向后兼容而设计的,而 android.widget.Toolbar 是当前的平台类型。
如果您不知道支持库是什么,请查看 this answer.
默认情况下 Android Studio 让您使用 AppCompatActivity,它是支持库的一部分,因此也需要一个支持工具栏。

为什么会出现编译错误?

因为setSupportActionBar(toolbar)中的参数是

android.support.v7.widget.Toolbar 而不是

android.widget.Toolbar

如何查看?

setSupportActionBarAppCompatActivity 的一部分。如果您想查看参数,只需覆盖 Activity 中的方法并删除导入即可。它将指示应导入哪个 class 以消除编译错误。

What is the distinction?

很明显。两者不同 class一个属于支持库,另一个不属于。

与 AppCompat 结合Activity

支持库中不断添加所有新功能,因此您将在所有 API 级别上拥有相同的功能。换句话说,支持库不断更新。例如,建议使用 android.support.v4.app.Fragment 与 AppcompatActivity.
结合使用 因此,所有 API 级别的兼容性可能是一个原因。

重点是如果你的Activity扩展了AppCompatActivity然后使用

  • android.support.v7.widget.Toolbar
  • android.support.v4.app.Fragment
  • android.support.v7.widget.RecyclerView 等等