如何运行从另一个片段的片段 [英] how to run a fragment from another fragment

查看:123
本文介绍了如何运行从另一个片段的片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主要活动(活动1),其中有一个膨胀抽屉式导航(带列表视图列表项)。抽屉通过一个片段(MenuFragment)上运行,所以我这样我就可以充气,这取决于项目选择的XML布局。现在我的问题是如何运行的另一个活动(活动2)当用户从抽屉中选择任何项目,因为抽屉被MenuFragment跑了,我可以从一个片段开始活动。任何帮助真的是AP preciated。先谢谢了。

I have a main activity (Activity 1) which has inflate a navigation drawer (with listview listing items). The drawer is run by a fragment (MenuFragment) so I am so I can inflate any xml layout depending on which item is selected. Now my problem is how to run another activity (Activity 2) when the user select any item from the drawer since the drawer is ran by the MenuFragment and I can start activity from a fragment. Any help is really appreciated. Thanks in advance.

推荐答案

一个常见的​​模式对这类问题的方法是提供一个监听器接口的每个片段,其中的活动需要在片段中有事通知。

A common pattern for this type of problem is to provide a listener interface for each fragment where the Activity needs to be notified when something within the fragment happens.

所以,你的菜单中的片段可能看起来是这样的:

So your menu fragment could look something like:

public class MenuFragment extends Fragment
{
    public interface Listener
    {
        void onDrawerItemSelected();
    }

    private Listener listener;

    public void setListener(Listener listener)
    {
        this.listener = listener;
    }

    // When drawer item selected, do something like
    //
    // if (listener != null)
    // {
    //    listener.onDrawerItemSelected();
    // }
}

您的活动看起来是这样的:

Your activity would look something like:

public class TestActivity extends Activity implements MenuFragment.Listener 
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        // MenuFragment fragment = ...;
        // fragment.setListener(this);
    }

    @Override
    public void onDestroy()
    {
        // MenuFragment fragment = ...;
        // fragment.setListener(null);
        super.onDestroy();
    }

    @Override
    public void onDrawerItemSelected()
    {
        // TODO launch other activity here
    }
}

在本质上,让你的活动带动展会。

In essence, let your Activity drive the show.

这篇关于如何运行从另一个片段的片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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