简体   繁体   English

如何在调用片段的方法中调用MainActivity?

[英]How can I call the MainActivity in a method that recalls fragments?

In MainActivity I have the following method that launches fragments. 在MainActivity中,我有以下方法启动片段。

@Override
public void onNavigationItemSelected(MenuItem item) {
    int id = item.id;
    Fragment fragmentToShow = null;
    if (id != 1){
        fragmentToShow = MoviesFragment.newIstance(item);
    }
    if (fragmentToShow != null){
        launchFragment(fragmentToShow, null);
    }
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(Gravity.LEFT);
}

If the element with id = 1 is clicked, the application must open the main activity but it is not a fragment: how can i do it? 如果单击id = 1的元素,则应用程序必须打开主活动,但它不是片段:我该怎么做?

Thank you guys for your help, i am a beginner who tries to learn: surely it will be easy to solve this my problem 谢谢你们的帮助,我是一个试图学习的初学者:肯定很容易解决我的问题

This method "onNavigationItemSelected" is being called from where? 这个方法“onNavigationItemSelected”是从哪里调用的?

As I understood this method comes from a Fragment and you wish to come back to the MainActivity, right? 据我所知,这个方法来自Fragment,你想回到MainActivity,对吧?

When you say "MainActivity" means that it is the launch activity then you could use onBackPressed to go to previous Activity. 当您说“MainActivity”意味着它是启动活动时,您可以使用onBackPressed转到上一个活动。

getActivity().onBackPressed(); getActivity()onBackPressed();

If that's not the question, please complement with more details. 如果这不是问题,请补充更多细节。 It would be helpfull :) 这会有所帮助:)

That is what you need 这就是你所需要的

@Override
public void onNavigationItemSelected(MenuItem item) {
    int id = item.id;

    if (id == 1) {
        Intent intent = new Intent(getcontext(), MainActivity.class);
        startactivity(intent‌​);
        return;
    }

    Fragment fragmentToShow = null;
    if (id != 1){
        fragmentToShow = MoviesFragment.newIstance(item);
    }
    if (fragmentToShow != null){
        launchFragment(fragmentToShow, null);
    }
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(Gravity.LEFT);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM