【问题标题】:Inconvertible type error from fragment to SupportMapFragment从片段到 SupportMapFragment 的不可转换类型错误
【发布时间】:2014-12-21 10:13:20
【问题描述】:

所以我有一个片段类:

public class MyMapFragmentActivity extends Fragment implements LocationListener,
        GoogleMap.OnMapClickListener, GoogleMap.OnMapLongClickListener {

在其中我定义了一个 SupportMapFragment:

private SupportMapFragment fragment;

我正在尝试使用 findFragmentById:

    @Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    FragmentManager fm = getChildFragmentManager();
    fragment = (SupportMapFragment) fm.findFragmentById(R.id.map);
    if (fragment == null) {
        fragment = SupportMapFragment.newInstance();
        fm.beginTransaction().replace(R.id.content_frame, fragment).commit();
    }
}

线

fragment = (SupportMapFragment) fm.findFragmentById(R.id.map);

尽管“片段”是 SupportMapFragment,但这会产生不可转换的类型错误: 无法将 android.app.fragment 转换为 com.google.android.gms.maps.SupportMapFragment !

我正在使用片段布局:

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.SupportMapFragment" />

【问题讨论】:

    标签: android android-fragments


    【解决方案1】:

    如果您使用兼容性库 - 使用 getSupportFragmentManager().findFragmentById(R.id.fragment); 否则从 android.app.Fragment 扩展而不是 android.support.v4.app.fragment

    【讨论】:

      【解决方案2】:

      您正在混合支持片段和不支持片段管理器。请改用 SupportFragmentManager。

      【讨论】:

      • 我在任何开发文档中都没有看到“SupportFragmentManager”并且它没有出现在代码提示中?
      • 它在 android 支持库中。它是将片段(和其他一些东西)反向移植到 2.x 的代码。或者,您可以使用 MapFragment 而不是 SupportMapFragment,但这会在 2.x 上破坏您的应用程序。基本上,要在 2.x 上工作,只使用 Support 类。要仅在 4.0+ 上工作,您可以使用普通版本。但切勿将两者混为一谈。
      • 你能在谷歌网站上找到支持参考吗?我看不到它;这个答案有 70 分,这就是我尝试的方式:stackoverflow.com/questions/14565460/…
      • 只是谷歌你命名的例外。它是由混合支持和非支持片段引起的。两者不能混用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-11
      • 2018-02-14
      • 2019-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-02
      相关资源
      最近更新 更多