如何在 Fragment 中实现 GoogleMap?
我正在尝试开发相同的东西,但无法执行 getMap(),因为 SupportMapFragment(在执行行 (SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById( R.id.map) 时)返回空对象。
我试过扩展 MapFragment 和 SupportMapFragment 而不是 Fragment,但它们没有用...
我只是不想创建一个新的 Activity 来显示 map :我只想显示一个 map 而不是我的主要 Activity 。我可以实现我的目标吗?
我有一个扩展 ActionBarActivity 的主要 Activity ,它替换容器内的 fragment (取决于用户在抽屉上的选择,替换并显示 X 或 Y fragment )。我拥有 2 个正在运行的 fragment ,但我无法实现在 fragment 内操作 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 对象为空,因此 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();
}
最佳答案
您好,您可以引用我的回答here
你需要这样调用...
SupportMapFragment fragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapaPrincipal);
mMapa = fragment.getMap();
关于java - 如何在 Fragment 中实现 Google Maps 并使用 GoogleMap 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26863507/