在我的Android应用中,我在一个扩展Fragment的类中显示了一个Google Maps地图。
目前,只显示地图,但我无法从SupportFragmentManager获取地图。
我所做的是将Android Studio中的MapActivity调整到我的应用程序。
这是我的代码:
public class Tab2 extends Fragment {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private double latitud_del_hotel, longitud_del_hotel;
private String nombre_del_hotel;
private GoogleMap map;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_2, container, false);
//setUpMapIfNeeded();
return v;
}
@Override
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
}
我收到一个异常:java.lang.NullPointerException 在com.solinpromex.elpasojuarezexperience.Tab2.setUpMapIfNeeded
我尝试从两种方法调用方法setUpMapIfNeeded()
:onCreateView和onActivityCreated。两种情况都会引发异常。
如果我删除setUpMapIfNeeded()
,则会显示地图,但我想添加地图对象。
欢迎任何帮助..
修改
从logcat完成异常日志:
09-16 00:34:09.614 13999-13999/com.solinpromex.elpasojuarezexperience E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.solinpromex.elpasojuarezexperience, PID: 13999
java.lang.NullPointerException
at com.solinpromex.elpasojuarezexperience.Tab2.setUpMapIfNeeded(Tab2.java:66)
at com.solinpromex.elpasojuarezexperience.Tab2.onActivityCreated(Tab2.java:57)
at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1797)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:979)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490)
at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1105)
at android.support.v4.view.ViewPager.populate(ViewPager.java:951)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1473)
at android.view.View.measure(View.java:16857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:742)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
at android.view.View.measure(View.java:16857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:124)
at android.view.View.measure(View.java:16857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:742)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
at android.view.View.measure(View.java:16857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
at android.view.View.measure(View.java:16857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1621)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:742)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:607)
at android.view.View.measure(View.java:16857)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5378)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:340)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2332)
at android.view.View.measure(View.java:16857)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2271)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1334)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1532)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1211)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6282)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:788)
at android.view.Choreographer.doCallbacks(Choreographer.java:591)
at android.view.Choreographer.doFrame(Choreographer.java:560)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:774)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
at dalvik.system.NativeStart.main(Native Method)
编辑2
布局文件tab_2
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"
android:id="@+id/map"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
</LinearLayout>
</RelativeLayout>
答案 0 :(得分:10)
如果您使用最新的GooglePlayServices
,则可以使用getMapAsync
功能,该功能会自动初始化地图系统和视图。
在布局中也使用MapView
这是我在片段中添加地图的方式。
public class MapFragment extends Fragment implements OnMapReadyCallback {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_tab_fragment1, container, false);
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
SupportMapFragment fragment = new SupportMapFragment();
transaction.add(R.id.mapView, fragment);
transaction.commit();
fragment.getMapAsync(this);
return view;
}
@Override
public void onMapReady(GoogleMap map) {
//map is ready
map.addMarker(...
}
}
x2中的<com.google.android.gms.maps.MapView
android:id="@+id/mapView"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
要使用最新的GooglePlayService,请将其放入gradle中
compile 'com.google.android.gms:play-services:8.3.0'
答案 1 :(得分:1)
请遵循此代码。希望这可能有所帮助。根据您的要求在必要时进行更改。我认为您将此地图视图添加为标签视图中的片段。
public class DealsCloseBy extends Fragment {
SupportMapFragment mMapView;
private GoogleMap googleMap;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.fragment_deals_close_by, container, false);
mMapView = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map));
mMapView.onCreate(savedInstanceState);
mMapView.onResume();// needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
googleMap = mMapView.getMap();
// latitude and longitude
double latitude = 13.0294278;
double longitude =80.24667829999999;
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps").icon(BitmapDescriptorFactory.fromResource(R.mipmap.map_pin));
// Changing marker icon
// marker.icon(BitmapDescriptorFactory
// .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(13.0294278, 80.24667829999999)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Perform any camera updates here
return v;
}
}
在xml文件中,使用: -
代替地图片段 <fragment
android:id="@+id/map"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
class="com.google.android.gms.maps.SupportMapFragment"/>