我正在使用google maps v2和actionbar标签片段。一切都很好但我需要通过从第一个标签(第一个片段)传递lat long来更新我的地图位置,因为地图位于第二个标签上。我通过构造函数传递latlong。 首先问题是在viewpager上处理片段的生命周期,但是通过跟随this教程,问题就解决了。现在我在" onFragmentPause"中使用地图更新方法但它是抛出零点异常,如果我将它放在" onViewCreate()"代码详细显示。
跟踪片段:
public class Track extends Fragment implements FragmentLifecycle {
private static GoogleMap mMap;
private static Double latitude, longitude;
private static String vAddress;
private static View Track;
DataHandler dh;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if(activity instanceof DataHandler)
{
dh = (DataHandler)activity;
}
else
throw new ClassCastException();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
Track = inflater.inflate(R.layout.activity_track, container, false);
return Track;
}
public void setUpMapIfNeeded() {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getFragmentManager()
.findFragmentById(R.id.location_map)).getMap();
setUpMap();
}
private static void setUpMap() {
try{
mMap.setMyLocationEnabled(true);
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(vAddress).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker2)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,
longitude), 12.0f));
}
catch(Exception e){
Log.wtf("this error", "ok");
}
}
public void onDestroyView() {
super.onDestroyView();
try {
Fragment fragment = (getFragmentManager().findFragmentById(R.id.location_map));
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onPauseFragment() {
}
@Override
public void onResumeFragment() {
Log.i("state", "onResumeFragment()");
latitude= 73.023333; //getting latitude from first tab(fragment)by calling constructor
longitude= 67.939322;
vAddress = "some address";
setUpMapIfNeeded();
}
现在如果我在onCreateView中放置setUpMapIfNeeded()并更改旋转,它会重新创建并更新位置,但在放入onResumeFragment()时会出错。 如果我无法有效描述,请帮助我,对不起。
错误 因为logcat在第48行显示错误 .findFragmentById(R.id.location_map))的GetMap();
这是 Activity_Track
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<fragment
android:id="@+id/location_map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</LinearLayout>
如果我从静态值更改为此值,则会在行纬度= dh.getLat();
行崩溃给出一个null null点异常@Override
public void onResumeFragment() {
Log.i("state", "onResumeFragment()");
latitude= dh.getLat(); //getting latitude from first tab(fragment)by calling constructor
longitude= dh.getLong();
vAddress = dh.getAddress();
setUpMap();
}