Mapfragment findFragmentById始终为null

use*_*854 10 android google-maps fragment mapfragment

我有问题访问地图的片段.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>
Run Code Online (Sandbox Code Playgroud)

并且在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();
}
Run Code Online (Sandbox Code Playgroud)

Dha*_*mar 21

用这种方式:

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

            map = mapFrag.getMap();
Run Code Online (Sandbox Code Playgroud)

这里是带有示例的完整代码:

  • 请注意,如果您使用Android支持库来显示地图,请确保包含地图片段的布局xml文件应具有到com.google.android.gms.maps.SupportMapFragment的android:name属性值.而不是`com.google.android.gms.maps.MapFragment`,否则它将无法工作并继续返回`null` (11认同)