MapFragment 的 findFragmentById 始终为 null。

10

我无法访问地图片段。 getFragmentManager().findFragmentById(R.id.map)) 总是返回 null。 我不知道原因。 问题出在哪里?

谢谢!

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

        <TextView
            android:id="@+id/tvNombreCentro"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="10dp"
            android:text="Large Text"
            android:textAppearance="?android:attr/textAppearanceLarge" />


    <fragment
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:tag="tag_fragment_map" />

    </LinearLayout>

在setContentView之后的活动中,我尝试访问地图,但是我收到了一个异常。

public class Mapa extends Activity {
private GoogleMap mMap;
private ActionBar ab;

private TextView tvNombreCentro;
private TextView tvTelefonoValor;
private TextView tvEMailValor;
private TextView tvWebValor;
private TextView tvDireccionValor;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.mapa_centro);
    GoogleMap mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
            .getMap();
}
4个回答

21

11
请注意,如果您使用Android支持库来显示地图,请确保包含地图片段的布局xml文件应具有android:name属性值为com.google.android.gms.maps.SupportMapFragment而不是com.google.android.gms.maps.MapFragment,否则它将无法正常工作并会持续返回“null”。 - Aryo
太好了!它帮助了我! - mr_ivan777

2
如果问题还没有解决,请尝试以下方法:
由于您正在使用 SupportMapFragment,在检索地图时,请使用以下方法:
   GoogleMap mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

此外,更改


   public class Mapa extends Activity {

为了

   public class Mapa extends FragmentActivity {

抱歉耽搁了。答案是正确的,但我不需要更改extends,只需更改getSupportFragmentManager即可。谢谢! - user1852854

1

当我尝试获取MapFragment时,遇到了类似的问题,因为设备没有更新Google Play服务,导致返回null。


1

布局变更

android:name = "com.google.android.gms.maps.SupportMapFragment"

通过

android:name = "com.google.android.gms.maps.MapFragment" 进行更改。

或者,您可以使用 getSupportFragmentManager() 代替 getFragmentManager()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接