问题
I have inflated layout content_main.xml
to view
variable vi
How should I get the fragment
from this inflated view?
Maybe something like :
SupportMapFragment mapFragment = (SupportMapFragment) inflatedView.getSupportFragmentManager()
.findFragmentById(R.id.map);
public void getMapFragment()
{
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vi = inflater.inflate(R.layout.content_main, null);
CoordinatorLayout mainL = (CoordinatorLayout) findViewById(R.id.main_view);
mainL.removeAllViews();
mainL.addView(vi);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
Thank you for the answer!
回答1:
If your inflated layout contains a <fragment/>
tag, i.e. if your fragment is inflated the XML way with the activity it resides in, then you can "get" the fragment via:
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
You ask the FragmentManager
to find your fragment, which is different from asking a View
to find it.
If your inflated layout contains a fragment which you added programmatically, i.e. you put a tag in the XML of your activity and used a FragmentTransaction
to add the fragment to your view (with a TAG!), then you can "get" the fragment via:
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentByTag("MAP");
See this source for further information about fragments.
来源:https://stackoverflow.com/questions/47587973/how-to-get-fragment-from-inflated-layout