问题
I'm writing an Android application that targets 4.0 and up and I'm using Google Maps v2. I'd like to set the contents of an InfoWindow
with a Fragment
. Does anyone know if it's possible?
My class implements InfoWindowAdapter
and here's the relevant code:
//
// InfoWindowAdapter interface
//
@Override
public View getInfoContents (Marker marker) {
LinearLayout layout = new LinearLayout(this.getActivity());
LayoutInflater inflater = (LayoutInflater) this.getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.map_details, layout);
MapDetailsFragment frag = new MapDetailsFragment();
// TODO: How to add this fragment to v???
return v;
}
@Override
public View getInfoWindow (Marker marker) {
return null;
}
I've tried the following code after instantiating frag
:
this.getFragmentManager().beginTransaction().replace(R.id.fragment_map_details, frag).commit();
But R.id.fragment_map_details
is from the R.layout.map_details
and thus the FragmentManager
doesn't know anything about it yet.
Any pointers would be greatly appreciated!
回答1:
The view returned from adapter is not a live view, but is transformed into a bitmap, so no code associated with this view (like button clicks) will ever execute.
The same case would be for fragments, so you may stop trying that and instead create a layout that binds together map_details and fragment layout. A use of include in xml will probably work.
回答2:
I've not seen anyone achieve it and I don't think it is possible as it's a simple view that is created for you, meaning a lot happens behind your back.
回答3:
Three suggestions:
The transaction and the commit is asynchronous. You could try calling http://developer.android.com/reference/android/app/FragmentManager.html#executePendingTransactions(). However, I got exceptions at one point when I tried to use that. But you might have more luck with it.
Otherwise, you could try adding the fragment as regular subview to your container by replacing
R.id.fragment_map_details
with the view returned fromfrag.getView()
. That's just a wild guess, however. Maybe you're not supposed to make use of that return value in that way. (I've gotten a bit cautious when it comes to Android's API...)From https://developers.google.com/maps/documentation/android/infowindows (under "Custom info windows"):
To update the info window later (for example, after an image has loaded), call showInfoWindow().
So, if you can find a way to get notified when the fragment transaction is complete then you could call that method to update the info window.
来源:https://stackoverflow.com/questions/17015646/add-android-fragment-to-infowindow-contents