从片段到SupportMapFragment的不可转换类型错误

时间:2014-12-21 10:13:21

标签: android android-fragments

所以我有一个片段类:

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" />

2 个答案:

答案 0 :(得分:4)

如果您使用兼容性库,请使用getSupportFragmentManager().findFragmentById(R.id.fragment);,否则从android.app.Fragment而不是android.support.v4.app.fragment延伸。

答案 1 :(得分:2)

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

相关问题