How to get fragment from inflated layout

寵の児 提交于 2019-12-20 05:40:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!