Можно ли показать вид карты внутри фрагмента диалога?

У меня есть фрагмент диалогового окна, в котором я хочу показать свою карту и отметить широту и журнал, которые у меня с собой. Но я получаю свой getMap() как NULL. Это то, что я сделал

public class EventDetailsDialogFragment extends DialogFragment{
    TextView title, desc, sdate, edate, room, loctn;
    FeedObjModel selectedFeedObject;
    Date netDate;
    SimpleDateFormat sdf;
    GoogleMap theMap;
    MarkerOptions markerOptions;
    FragmentActivity myContext;

    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
    }

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View view = inflater.inflate(R.layout.event_details_dialog_layout, container);

    title = (TextView) view.findViewById(R.id.title_event_details_TV);
    desc = (TextView) view.findViewById(R.id.description_event_details_TV);
    sdate = (TextView) view.findViewById(R.id.start_date_event_details_TV);
    edate = (TextView) view.findViewById(R.id.end_date_event_details_TV);
    loctn = (TextView) view.findViewById(R.id.locEdTV);


    long timestamp1 = Long.parseLong(selectedFeedObject.eventstartDate);
    long timestamp2 = Long.parseLong(selectedFeedObject.eventendDate);
    try{ 
        sdf = new SimpleDateFormat("MMM dd, yyyy");
        netDate = (new Date(timestamp1*1000));
        sdate.setText(sdf.format(netDate));  
        netDate = (new Date(timestamp2*1000));
        edate.setText(sdf.format(netDate));  
    } catch(Exception ex){

        }

    getDialog().setTitle(""+selectedFeedObject.subject);
    title.setText(selectedFeedObject.subject);
    desc.setText(selectedFeedObject.eventDescription);
    loctn.setText(selectedFeedObject.eventLocation);

/*  theMap = ((SupportMapFragment) getActivity().getSupportFragmentManager()
            .findFragmentById(R.id.mapED))
            .getMap();*/

    SupportMapFragment fragment = new SupportMapFragment();
    FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
    transaction.add(R.id.mapED, fragment).commit(); 
    theMap = fragment.getMap();

    Log.v("theMap1", ""+theMap);

        Double lng = Double.parseDouble(selectedFeedObject.eventlongitude);
        Double lat = Double.parseDouble(selectedFeedObject.eventlatitude);
        LatLng latLng = new LatLng(lng, lat);
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title(selectedFeedObject.eventLocation);

    Log.v("markerOptions", ""+markerOptions);

        theMap.addMarker(markerOptions);
        theMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
        CameraUpdate center = CameraUpdateFactory
                .newLatLng(new LatLng(lat, lng));
        CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
        theMap.moveCamera(center);
        theMap.animateCamera(zoom);
    return view;

}


public void setEventDetails(FeedObjModel _selectedFeedObject) {
    // TODO Auto-generated method stub
    selectedFeedObject = _selectedFeedObject;
}
}

я получаю "карту" как NULL

.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="5dp"
    android:paddingLeft="10dp"
    android:paddingRight="5dp"
    android:paddingTop="5dp" >

    <TextView
        android:id="@+id/title_event_details_TV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Description" 
        android:textSize="16sp"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/description_event_details_TV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start Date and Time"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/start_date_event_details_TV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="End Date and Time"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/end_date_event_details_TV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Location" 
        android:textSize="16sp"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/locEdTV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <FrameLayout
        android:id="@+id/mapED"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="com.google.android.gms.maps.SupportMapFragment"
         />

</LinearLayout>

person Elizabeth    schedule 06.08.2014    source источник


Ответы (2)


Я написал следующий код в onResume(), теперь он работает ... я не знаю, правильно ли это.

    @Override
public void onResume() {

    // TODO Auto-generated method stub
    super.onResume();
    theMap = mapView.getMap();
    Log.v("theMap1", ""+theMap);
    Log.v("lng", ""+lng);
    Log.v("lat", ""+lat);
    latLng = new LatLng(lng, lat);
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title(locString);

    Log.v("markerOptions", ""+markerOptions);
    theMap.addMarker(markerOptions);
    theMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
     CameraUpdate center=
                CameraUpdateFactory.newLatLngZoom(new LatLng(lat,
                        lng),16);
    CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
    theMap.moveCamera(center);
    theMap.animateCamera(zoom);

}

в oncreateview

mapView = CustomMapFragmentForEventDetails.newInstance();
    FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
    fragmentTransaction.add(R.id.mapED, mapView);
    fragmentTransaction.commit();

        lng = Double.parseDouble(selectedFeedObject.eventlongitude);
        lat = Double.parseDouble(selectedFeedObject.eventlatitude);

и в CustomMapFragmentForEventDetails

public class CustomMapFragmentForEventDetails extends SupportMapFragment {
    SupportMapFragment mSupportMapFragment;
    GoogleMap googleMap;
    OnMapReadyListener mOnMapReadyListener;
    @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
     {
      super.onCreateView(inflater, container, savedInstanceState);
      Log.v("Inside CustomMapFrag", "Success");
      View root = inflater.inflate(R.layout.event_details_dialog_layout, null, false); 
      initilizeMap();
      return root;
     }

    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        mOnMapReadyListener = (OnMapReadyListener) activity;
    }

    private void initilizeMap()
     {
      mSupportMapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.mapED);
      if (mSupportMapFragment == null) {
       FragmentManager fragmentManager = getFragmentManager();
       FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
       mSupportMapFragment = SupportMapFragment.newInstance();
       fragmentTransaction.replace(R.id.mapED, mSupportMapFragment).commit();
         }
      if (mSupportMapFragment != null)
      {
          googleMap = mSupportMapFragment.getMap();
       if (googleMap != null)

       {
           Log.v("MAP GOOGLE in CustomMApfragment", ":: "+googleMap);
           mOnMapReadyListener.onMapReady(googleMap);
       }

      }
     }
    public static interface OnMapReadyListener {

        void onMapReady(GoogleMap googleMap);
    }
}
person Elizabeth    schedule 07.08.2014

Я предполагаю, что это потому, что даже если Transaction фрагмента карты зафиксирован, он не выполняется немедленно. Вы должны использовать: FragmentManager.executePendingTransactions() таким образом:

SupportMapFragment fragment = new SupportMapFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.mapED, fragment).commit();
getFragmentManager().executePendingTransactions();
theMap = fragment.getMap();
person Antoine Marques    schedule 07.08.2014
comment
Теперь я получаю java.lang.IllegalStateException: Рекурсивная запись для ошибки executePendingTransactions ... - person Elizabeth; 07.08.2014
comment
К сожалению, это потому, что onCreateView уже выполняется в рамках транзакции. Я объяснил, что транзакция фрагмента карты выполняется асинхронно. вы можете : - person Antoine Marques; 07.08.2014
comment
1) Используйте Fragment.getChildFragmentManager(), если ваш уровень API больше 17. 2) Используйте метод async, как описано в этом сообщении: stackoverflow.com/questions/7700226/. Это также можно сделать с помощью getActivity.runOnUiThread(Runnable) - person Antoine Marques; 07.08.2014
comment
спасибо ... у меня есть солнце .. я не знаю, что это правильный способ ... может быть, по крайней мере, длина ... но это решено ... ответ, приведенный ниже - person Elizabeth; 07.08.2014