简体   繁体   English

如何从导航抽屉调用主要活动

[英]How to call main activity from the navigation drawer

I have created an navigation drawer which has an home option which i want to redirect it to the main activity.我创建了一个导航抽屉,它有一个主页选项,我想将它重定向到主要活动。 All the rest options open up an fragment.所有其余选项打开一个片段。

I am getting an error saying getactivity is not defined.我收到一条错误消息,指出未定义 getactivity。 Is it possible to call the activity from the activity itself.是否可以从活动本身调用活动。 If yes, can i get the code.如果是的话,我可以得到代码。

I have removed some part of the code as it is default while creating navigation drawer.我已经删除了部分代码,因为它是创建导航抽屉时的默认代码。 Here is my main activity:这是我的主要活动:

private void displaySelectedScreen(int itemId) {

    //creating fragment object
    Fragment fragment = null;

    //initializing the fragment object which is selected
    switch (itemId) {
        case R.id.nav_home:
            Intent in = new Intent(this.getActivity(), MainActivity.class);
            startActivity(in);
        case R.id.nav_contact_us:
            fragment = new ContactUs();
            break;
        case R.id.nav_how_to_convert:
            fragment = new HowAppWorks();
            break;
        case R.id.nav_team:
            fragment = new Team();
            break;
    }

    //replacing the fragment
    if (fragment != null) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.content_frame, fragment);
        ft.commit();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {

    displaySelectedScreen(item.getItemId());
    return true;
}

As You said you are in MainActivity and still you want to move in MainActivity infect it is bad Approach, you can just refresh data or reload views only.. But if still want that here is the problem in your code as assuming its MainActivity Code use MainActivity.this in context not this.正如您所说的,您在 MainActivity 中,但仍想在 MainActivity 中移动感染它是不好的方法,您只能刷新数据或重新加载视图.. MainActivity.this 在上下文中不是 this。 getActivity();获取活动();

Intent in = new Intent(MainActivity.this, MainActivity.class);
startActivity(in);

NB: The Activity class doesn't have a getActivity() method注意:Activity 类没有 getActivity() 方法

startActivity(new Intent(MainActivity.this, MainActivity.class));
finish()

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

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