如何从膨胀的布局中获取片段 [英] How to get fragment from inflated layout

查看:58
本文介绍了如何从膨胀的布局中获取片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将布局content_main.xml夸大为view变量vi

如何从这个膨胀的视图中获取fragment?

How should I get the fragment from this inflated view?

也许是这样的:

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);
}

谢谢您的回答!

推荐答案

如果展开后的布局包含<fragment/>标记,即,如果您的片段通过其所驻留的活动以XML方式进行了展开,则可以获取"片段通过:

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);

您要求FragmentManager查找片段,这不同于要求View查找片段.

You ask the FragmentManager to find your fragment, which is different from asking a View to find it.

如果膨胀后的布局包含以编程方式添加的片段,即您在活动的XML中添加了标签,并使用FragmentTransaction将片段添加到视图中(带有TAG!),那么您可以通过以下方式获取"片段:

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.

这篇关于如何从膨胀的布局中获取片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆