Google 的 SupportMapFragment 类型转换异常与 v4 片段

Google's SupportMapFragment type cast exception with v4 Fragment

不可转换的类型;无法将 'android.support.v4.app.Fragment' 转换为 'com.google.android.gms.maps.SupportMapFragment'

我为 google 地图集成创建了新项目,编辑器中也有(在正在进行的项目中首次尝试)相同类型的强制转换异常。已经看到许多其他类似的问题,但那些是针对 android.app.Fragment with SupportMapFragment 的类型转换异常,甚至他们接受的答案是使用 android.support.v4.app.Fragment with SupportMapFragment 来解决错误,但在我的案例,同样是给我一个错误。 (所以这可能看起来是重复的,但事实并非如此。)。请为此提出解决方案。

深​​入研究后,发现在我的例子中,SupportMapFragment 扩展了 Fragment,它属于 Jetpack 的 androidx

我的 AppCompatActivitygetSupportFragmentManager().findFragmentById(id) 方法返回 Fragment,所有这些都属于传统的 android 包。

根据 docs

androidx 包与 android 包完全不同但平行

AndroidX maps the original support library API packages into the androidx namespace. Only the package and Maven artifact names changed; class, method, and field names did not change.

所以,我得到 type-cast-exception 如下语句:

SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);

异常:

Inconvertible types; cannot cast 'android.support.v4.app.Fragment' to 'com.google.android.gms.maps.SupportMapFragment'

为了解决这个问题,我需要将我现有的项目迁移到 androidx