如何在片段中实现GoogleMap?
我正在尝试开发相同的东西,但无法执行getMap(),因为SupportMapFragment(执行该行时(SupportMapFragment)getActivity()。getSupportFragmentManager()。findFragmentById(.R.id.map))返回一个空对象。
我试过扩展MapFragment和SupportMapFragment而不是Fragment,但是它们没有用...
我只是不想创建一个新的活动来显示地图:我只想显示一个Map而不是我的主要活动。我可以实现我的目标吗?
我有一个扩展ActionBarActivity的主要活动,该活动替换了容器内的片段(取决于用户在抽屉上的选择,X或Y片段将被替换并显示)。我拥有2个可工作的片段,但无法实现操作片段内部的GoogleMap对象的目标。
那就是我的mapa.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mapaPrincipal"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
那是我的FragmentMapa类:
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.ingartek.bizkaimove.R;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentMapa extends Fragment {
private GoogleMap mMapa;
public FragmentMapa() {
// TODO Auto-generated constructor stub
}
@Override
public void onAttach (Activity activity) {
super.onAttach(activity);
}
@Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.mapa, container, false);
mMapa = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.mapaPrincipal)).getMap();
return rootView;
}
高亮显示的行不起作用,因为SupportMapFragment对象为null,因此getMap()崩溃。
有什么帮助吗?提前致谢。
对于遇到像我的问题的任何人:您不应使用getSupportFragmentManager(),而应使用getChildFragmentManager()。这应该保持这种方式:
@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.mapa, container, false);
setupMapIfNeeded();
return rootView;
}
private void setupMapIfNeeded() {
if( mMapa == null ){
SupportMapFragment smf = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapaPrincipal);
if( smf != null ){
Toast.makeText(getActivity(), "Let's go!!", Toast.LENGTH_SHORT).show();
mMapa = smf.getMap();
}else{
Toast.makeText(getActivity(), "SMF is null...", Toast.LENGTH_SHORT).show();
}
if( mMapa != null ){
setupMap();
}
}
}
private void setupMap() {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "Configure the map", Toast.LENGTH_SHORT).show();
}
嗨,你可以在这里参考我的答案
你需要这样打...
SupportMapFragment fragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapaPrincipal);
mMapa = fragment.getMap();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句