如何通过背压完美地处理底部导航

时间:2017-05-09 12:58:10

标签: android android-layout android-fragments bottomnavigationview

我正在使用底部导航栏,但我没有得到完美的底部导航栏。

我的MainActivity课程:

public class MainActivity extends AppCompatActivity {

    private static final String SELECTED_ITEM = "selected_item";

    private BottomNavigationView bottomNavigationView;
    private Toolbar toolbar;
    private MenuItem menuItemSelected;
    private int mMenuItemSelected;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                selectFragment(item);
                return true;
            }
        });

        //Always load first fragment as default
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.frameLayout, new AnnouncementFragment());
        fragmentTransaction.commit();

        if (savedInstanceState != null) {
            mMenuItemSelected = savedInstanceState.getInt(SELECTED_ITEM, 0);
            menuItemSelected = bottomNavigationView.getMenu().findItem(mMenuItemSelected);
        } else {
            menuItemSelected = bottomNavigationView.getMenu().getItem(0);
        }

        selectFragment(menuItemSelected);
    }

    private void selectFragment(MenuItem item) {
        Fragment fragment = null;
        Class fragmentClass;
        switch (item.getItemId()) {
            case R.id.action_announcement:
                fragmentClass = AnnouncementFragment.class;
                break;
            case R.id.action_menu:
                fragmentClass = MenuFragment.class;
                break;
            case R.id.action_menu_reports:
                fragmentClass = ReportFragment.class;
                break;
            case R.id.action_setting:
                fragmentClass = SettingFragment.class;
                break;

            default:
                fragmentClass = AnnouncementFragment.class;
        }

        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.frameLayout, fragment).commit();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt(SELECTED_ITEM, mMenuItemSelected);
        super.onSaveInstanceState(outState);
    }

我的背部压力也不正常:

 @Override
    public void onBackPressed() {
        MenuItem homeItem = bottomNavigationView.getMenu().getItem(0);
        if (mMenuItemSelected != homeItem.getItemId()) {
            selectFragment(homeItem);
        } else {
            super.onBackPressed();
        }
    }

我应该怎么做,因为底部菜单栏上的分布不均匀。如何正确维护菜单空间而不分布不均。

这里我附上了我在AVD上获得的结果 First I

Another Selection

20 个答案:

答案 0 :(得分:12)

试试这个

2.2.2

答案 1 :(得分:11)

根据Material Design 指南

  

在Android上,“后退”按钮不会在底部之间导航   导航栏视图。

编辑:Material Design链接不再提及后退按钮行为。

按后退按钮可以退出应用程序,这是默认行为,例如Google Photo ...

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content, fragment);
// note: there is NOT a addToBackStack call
fragmentTransaction.commit();

...或者将用户带到主页部分,然后再次按下,退出。

就个人而言,我发现这最后一种模式要好得多。

要获得它而不覆盖onBackPressed,您需要识别主片段并将其与所有其他

区分开来
navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.navigation_home:
                viewFragment(new HomeFragment(), FRAGMENT_HOME);
                return true;
            case R.id.navigation_page_1:
                viewFragment(new OneFragment(), FRAGMENT_OTHER);
                return true;
            case R.id.navigation_page_2:
                viewFragment(new TwoFragment(), FRAGMENT_OTHER);
                return true;
        }
        return false;
    }
});

您现在要做的是编写必须的viewfragment方法:

  1. 知道之前 commit
  2. 中有多少片段
  3. 如果片段“家庭类型”,请先将其保存到堆栈中 commit

  4. 在堆栈减少时添加OnBackStackChangedListener (即当我按下时),删除所有碎片 “家庭类型”(POP_BACK_STACK_INCLUSIVE),将我们带回家庭片段

  5. 在带注释的完整方法下面

    private void viewFragment(Fragment fragment, String name){
        final FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.content, fragment);
        // 1. Know how many fragments there are in the stack
        final int count = fragmentManager.getBackStackEntryCount();
        // 2. If the fragment is **not** "home type", save it to the stack
        if( name.equals( FRAGMENT_OTHER) ) {
            fragmentTransaction.addToBackStack(name);
        }
        // Commit !
        fragmentTransaction.commit();
        // 3. After the commit, if the fragment is not an "home type" the back stack is changed, triggering the
        // OnBackStackChanged callback
        fragmentManager.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {
                // If the stack decreases it means I clicked the back button
                if( fragmentManager.getBackStackEntryCount() <= count){
                    // pop all the fragment and remove the listener
                    fragmentManager.popBackStack(FRAGMENT_OTHER, POP_BACK_STACK_INCLUSIVE);
                    fragmentManager.removeOnBackStackChangedListener(this);
                    // set the home button selected
                    navigation.getMenu().getItem(0).setChecked(true);
                }
            }
        });
    }
    

答案 2 :(得分:5)

这可能有点晚了,但我认为最好的方法就是这么简单。

 @Override
public void onBackPressed() {
    if (mBottomNavigationView.getSelectedItemId() == R.id.action_home) {
        super.onBackPressed();
    } else {
        mBottomNavigationView.setSelectedItemId(R.id.action_home);
    }
}

我希望它有帮助并且编码愉快:)。

答案 3 :(得分:5)

@Override
    public void onBackPressed() {
        BottomNavigationView mBottomNavigationView = findViewById(R.id.navigation);
        if (mBottomNavigationView.getSelectedItemId() == R.id.navigation_home)
        {
            super.onBackPressed();
            finish();
        }
        else
        {
            mBottomNavigationView.setSelectedItemId(R.id.navigation_home);
        }
    }

答案 4 :(得分:4)

onBackPressed对我不起作用。所以这就是我用的。

 @Override
 protected void onResume() {
    super.onResume();
    bottomNavigationView.getMenu().getItem(0).setChecked(true);
 }

答案 5 :(得分:2)

最好的方法是:在主页按钮中,应用程序关闭,而在另一个按钮中,则返回主页按钮。

下面我放我的代码:

首先,我在导航视图中加载主页按钮:

private void loadFragment(Fragment fragment) {
    Toast.makeText(this, "load", Toast.LENGTH_SHORT).show();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.frame_container, fragment, TAG_FRAGMENT);
    transaction.commit();
}

,请记住不要拨打addToBackStack()。 然后通过onBackPressed()处理情况:

@Override
public void onBackPressed() {
    if (navigation.getSelectedItemId() == R.id.bottomAkhbar) {
        super.onBackPressed();
    } else {
        navigation.setSelectedItemId(R.id.bottomAkhbar);
    }
}

答案 6 :(得分:1)

根据您的要求,您将使用导航片段,您可以使用带有视图寻呼机的Tablayout并进行底部导航。

<android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="60dp"></android.support.design.widget.TabLayout>

然后使用标签布局设置viewpager,并在活动中为tablayout添加图标

tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    viewPager = (ViewPager) findViewById(R.id.controller_pager);
    viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
    viewPager.setOffscreenPageLimit(4);
    tabLayout.setupWithViewPager(viewPager);
    tabLayout.getTabAt(0).setIcon(R.drawable.selector_home);
    tabLayout.getTabAt(1).setIcon(R.drawable.selector_contact);
    tabLayout.getTabAt(2).setIcon(R.drawable.selector_profile);
    tabLayout.getTabAt(3).setIcon(R.drawable.selector_settings);

现在可以通过点击tablayout来处理所有事情,它会正常工作     tabLayout.addOnTabSelectedListener(本);

答案 7 :(得分:1)

你可以试试这个/ 它对我有用

public class MainActivity extends BaseActivity {
    private HomeFragment homeFragment = new HomeFragment();
    private CartFragment cartFragment = new CartFragment();
    private ProfileFragment profileFragment = new ProfileFragment();
    private BottomNavigationView bottomNavigationView;  



@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
  
    super.onCreate(savedInstanceState);
    if (savedInstanceState == null){
        setContentView(R.layout.activity_main);
        bottomNavigationView = findViewById(R.id.bottom_nav);
        bottomNavigationView.setSelectedItemId(R.id.btnHome);
        FragmentTransaction homeFm = getSupportFragmentManager().beginTransaction();
        homeFm.replace(R.id.fragment_container, homeFragment);
        homeFm.commit();
        setupView();
    }

}

private void setupView() {
    bottomNavigationView.setOnNavigationItemSelectedListener(item -> {
        {
            switch (item.getItemId()) {
                case R.id.btnHome:
                    loadFragment(homeFragment);
                    return true;
                case R.id.btnCart:
                    loadFragment(cartFragment);
                    return true;
                case R.id.btnProfile:
                    loadFragment(profileFragment);
                    return true;
            }
            return false;
        }
    });
}


private void loadFragment(Fragment fragment) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.fragment_container, fragment);
    transaction.addToBackStack(null);
    transaction.commit();
}
@Override
public void onBackPressed() {
     if (bottomNavigationView.getSelectedItemId() == R.id.btnHome)
    {
        finish();
    }
    else
    {
        bottomNavigationView.setSelectedItemId(R.id.btnHome);
    }
}}

答案 8 :(得分:1)

尝试执行以下操作: 背面按: 从家庭片段退出应用程序。 从其他片段转到首页片段。

    //On Back Press if we are at a Fragment other than the Home Fragment it will navigate back to the
// Home Fragment. From Home Fragment it will exit the App.
@Override
public void onBackPressed() {
    int backStackEntryCount = getSupportFragmentManager().getBackStackEntryCount();
    if (backStackEntryCount == 0) {
        super.onBackPressed();  
    } else {
        goHome();
    }
}

    public void goHome() {
    //Following code will set the icon of the bottom navigation to active
    final BottomNavigationView mBottomNav = findViewById(R.id.nav_view);
    MenuItem homeItem = mBottomNav.getMenu().getItem(0);
    mBottomNav.setSelectedItemId(homeItem.getItemId());
    getSupportFragmentManager().popBackStackImmediate();

    //To delete all entries from back stack immediately one by one.
    int backStackEntry = getSupportFragmentManager().getBackStackEntryCount();
    for (int i = 0; i < backStackEntry; i++) {
        getSupportFragmentManager().popBackStackImmediate();
    }
    //To navigate to the Home Fragment
    final HomeFragment homeFragment = new HomeFragment();
    FragmentTransaction myFragmentTransaction = getSupportFragmentManager().beginTransaction();
    myFragmentTransaction.replace(R.id.nav_host_fragment, homeFragment, "HomeFrag Tag");
    myFragmentTransaction.commit();
}

答案 9 :(得分:1)

最新答案,但是就可以了。

假设您在 MainActivity 中有一个 BottomNavigation ,其中包含 4个片段

  1. FragmentA
  2. FragmentB
  3. FragmentC
  4. FragmentD

如果您要像这样将每个片段添加到Backstack:

和Kotlin:

 main_bottom_navigation.setOnNavigationItemSelectedListener { item ->
        var fragment: Fragment? = null
        when (item.itemId) {
            R.id.nav_a -> fragment = FragmentA()
            R.id.nav_b -> fragment = FragmentB()
            R.id.nav_c -> fragment = FragmentC()
            R.id.nav_d -> fragment = FragmentD()
        }

        supportFragmentManager
            .beginTransaction()
            .setCustomAnimations(R.anim.abc_fade_in, R.anim.abc_fade_out)
            .replace(R.id.home_content, fragment!!)
            .addToBackStack(fragment.tag)
            .commit()

        true
    }

您实际上并不需要覆盖 MainActivity 中的onBackPressed(),而是显式地对每个片段进行转换并分配 BottomNavigation ,如下所示:

FragmentA.kt

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    (activity as MainActivity).main_bottom_navigation.menu.getItem(0).isChecked = true
}

FragmentB.kt

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    (activity as MainActivity).main_bottom_navigation.menu.getItem(1).isChecked = true
}

FragmentC.kt

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    (activity as MainActivity).main_bottom_navigation.menu.getItem(2).isChecked = true
}

FragmentD.kt

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    (activity as MainActivity).main_bottom_navigation.menu.getItem(3).isChecked = true
}

像这样,片段堆栈将正确弹出,并在到达0时退出应用程序。

答案 10 :(得分:1)

我遇到了同样的问题,所以我使用这种方法解决了我的问题: 在我的主要活动中,我有一个底部导航栏和一个导航抽屉,我需要同步抽屉和底部导航中的项目:

我为我的主要片段和其他片段创建了一个方法: 我的主要片段替换器:

public void MainFragmentChanger(final Fragment fragment, final String TAG){
    if (main_page_fragment != null){
        fragmentTransaction = myFragmentManager.beginTransaction();
        fragmentTransaction.remove(main_page_fragment).commit();
    }
    if (main_drawer.isDrawerOpen()){
        main_drawer.closeDrawer();
    }
    new Handler().post(new Runnable() {
        @Override
        public void run() {
            main_page_fragment = fragment;
            main_page_fragment.setRetainInstance(true);
            fragmentTransaction = myFragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.main_container, main_page_fragment,TAG);
            fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            fragmentTransaction.commitAllowingStateLoss();
        }
    });
}

这是我的另一个片段替换器:

public void changeBottomFragment(final Fragment fragment, final String TAG){
    if (main_drawer.isDrawerOpen()){
        main_drawer.closeDrawer();
    }
    new Handler().post(new Runnable() {
        @Override
        public void run() {
            main_page_fragment = fragment;
            main_page_fragment.setRetainInstance(true);
            fragmentTransaction = myFragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.main_container, main_page_fragment);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            fragmentTransaction.commitAllowingStateLoss();
        }
    });
}

因此,在那之后,我需要同步抽屉和栏中的项目: 注意,我使用Mike Penz的材质导航抽屉,将com.ashokvarma.bottomnavigation.BottomNavigationBar用于导航栏。 这是用于此目的的方法:

public void changeNavAndBarStats(String tag){
    if (tag == "flash"){
        bottomNavigationBar.selectTab(2,false);
        main_drawer.setSelection(flashcards.getIdentifier(),false);
    }else if (tag == "dic"){
        bottomNavigationBar.selectTab(3,false);
        main_drawer.setSelection(dictionary.getIdentifier(),false);
    }else if (tag == "Home"){
        bottomNavigationBar.selectTab(0,false);
        main_drawer.setSelection(home.getIdentifier(),false);
    }
}

所以我这样称呼我的片段:

MainFragmentChanger(new MainPageFragment(),"Home");
                            bottomNavigationBar.selectTab(0,false);

changeBottomFragment(new FlashCardFragment(),"flash");
                            bottomNavigationBar.selectTab(2,false);

changeBottomFragment(new TranslateFragment(),"dic");
                            bottomNavigationBar.selectTab(3,false);

最后,我在片段的onResume方法中调用changeNavAndBarStatus:

((MainPageActivity)getContext()).changeNavAndBarStats("flash");

就是这样!你很好走!

答案 11 :(得分:1)

我在尝试了所有方法后都做了此操作,最后它起作用了-_-。我将这2个覆盖方法粘贴到了我通过底部导航进行的每个活动中。

  @Override
protected void onResume() {
    super.onResume();
    bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation_Menu_name);
    bottomNavigationView.getMenu().getItem(Menu_item_position).setChecked(true);

}

@Override
protected void onRestart() {
    super.onRestart();
    bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation_Menu_name);
    bottomNavigationView.getMenu().getItem(Menu_item_position).setChecked(true);
}

答案 12 :(得分:1)

大多数情况下,按返回按钮,后堆栈中的旧片段, 被召回。因此系统将其称为onCreateView()方法

添加此代码

val bottomNav = activity?.findViewById<BottomNavigationView>(R.id.activity_main_bottom_navigation)
    bottomNav?.selectedItemId = R.id.the_id_of_the_icon__that_represent_the_fragment

答案 13 :(得分:1)

请尝试此解决方案。 我对您提供的代码进行了更改。

我假设在第一次回复你的应用程序将回到主页片段(在你的情况下是公告片段),如果你再次按下,应用程序将关闭。

此流程也会反映在底部导航栏中。

public class MainActivity extends AppCompatActivity {
private static final String BACK_STACK_ROOT_TAG = "root_home_fragment";
private static final String SELECTED_ITEM = "selected_item";
private Fragment fragment;
private FragmentManager fragmentManager;
private BottomNavigationView bottomNavigationView;
private Toolbar toolbar;
private MenuItem menuItemSelected;
private int mMenuItemSelected;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
        = new BottomNavigationView.OnNavigationItemSelectedListener() {

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        boolean selected = false;
        switch (item.getItemId()) {
            case R.id.action_announcement:
                fragment = AnnouncementFragment.newInstance();
                selected =  true;
                break;
            case R.id.action_menu:
                fragment = MenuFragment.newInstance();
                selected =  true;
                break;
            case R.id.action_menu_reports:
                fragment = ReportFragment.newInstance();
                selected =  true;
                break;
        case R.id.action_setting:
        fragment = SettingFragment.newInstance();
                selected =  true;

        }
        if(fragment !=null){
            fragmentManager = getFragmentManager();
            switch (item.getItemId()) {
              case R.id.action_announcement:
                   // Pop every fragment from backstack including home fragment.
                   fragmentManager.popBackStack(BACK_STACK_ROOT_TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                   fragmentManager.beginTransaction()
                            .replace(R.id.content, fragment)
                            .addToBackStack(BACK_STACK_ROOT_TAG)
                            .commit();
                    break;
               default: 

                   fragmentManager.beginTransaction()
                            .replace(R.id.content, fragment)
                            .addToBackStack(null)
                            .commit();  
                   break;
           }
        }
        return selected;
    }

};


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
    bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

    //Always load first fragment as default
    bottomNavigationView.setSelectedItemId(R.id.action_announcement);

    if (savedInstanceState != null) {
        mMenuItemSelected = savedInstanceState.getInt(SELECTED_ITEM, 0);
        menuItemSelected = bottomNavigationView.getMenu().findItem(mMenuItemSelected);
    } else {
        menuItemSelected = bottomNavigationView.getMenu().getItem(0);
    }
}



@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putInt(SELECTED_ITEM, mMenuItemSelected);
    super.onSaveInstanceState(outState);
}

public void onBackPressed() {
    int count = getFragmentManager().getBackStackEntryCount();
    if(count >1){
        // We have lots of fragment on backstack to be popped.
        // Pop till the root fragment.
        getFragmentManager().popBackStack(BACK_STACK_ROOT_TAG, FragmentManager.POP_BACK_STACK_INCLUSIVE);
     bottomNavigationView.setSelectedItemId(R.id.action_announcement);
    }
    else{
        // Close the application when we are on home fragment.
        supportFinishAfterTransition();
    }
}
}

答案 14 :(得分:1)

试试这个。

getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {

            // Gets the previous global stack count
            int previousStackCount = mPreviousStackCount;

            // Gets a FragmentManager instance
            FragmentManager localFragmentManager = getSupportFragmentManager();

            // Sets the current back stack count
            int currentStackCount = localFragmentManager.getBackStackEntryCount();

            // Re-sets the global stack count to be the current count
            mPreviousStackCount = currentStackCount;

            boolean popping = currentStackCount < previousStackCount;

            if(popping){
                bottomNavigationView.getMenu().getItem(0).setChecked(true);
            }

        }
    });

答案 15 :(得分:1)

我遇到了同样的问题,但在这之后我得到了解决方案

首先将此代码粘贴到主活动中(使用底部导航栏的位置)

BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);

然后创建一个名为 BottomNavigationViewHelper 的类并粘贴以下代码。

public class BottomNavigationViewHelper {
public static void disableShiftMode(BottomNavigationView view) {
    BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
    try {
        Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
        shiftingMode.setAccessible(true);
        shiftingMode.setBoolean(menuView, false);
        shiftingMode.setAccessible(false);
        for (int i = 0; i < menuView.getChildCount(); i++) {
            BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
            //noinspection RestrictedApi
            item.setShiftingMode(false);
            // set once again checked value, so view will be updated
            //noinspection RestrictedApi
            item.setChecked(item.getItemData().isChecked());
        }
    } catch (NoSuchFieldException e) {
        Log.e("BNVHelper", "Unable to get shift mode field", e);
    } catch (IllegalAccessException e) {
        Log.e("BNVHelper", "Unable to change value of shift mode", e);
    }
}

}

希望有所帮助

答案 16 :(得分:1)

调用像这样的片段时使用 addToBackStack 方法,

   getSupportFragmentManager().beginTransaction().addToBackStack(null).add(R.id.content_home_nav,newFragment).commit();

在onBackPressed方法

中使用此代码
if (getSupportFragmentManager().getBackStackEntryCount() > 0 ){
        getFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
    }

答案 17 :(得分:0)

这是我在活动中处理后退压力的方法:

 RewriteRule ^([^/]+)/([^/]+)/(.+)$ viewblog.php?title=$1/$2/$1/$3 [L]

答案 18 :(得分:0)

此代码对我有用:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    OneSignal.startInit(this)
            .inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
            .unsubscribeWhenNotificationsAreDisabled(true)
            .init();

    bottomNavigationView = findViewById(R.id.bottomNav);
    frameLayout = findViewById(R.id.main_frame);

    homeFragment = new HomeFragment();
    aboutUsFragment = new AboutUsFragment();
    recipesFragment = new RecipesFragment();
    knowledgeFragment = new KnowledgeFragment();
    contactFragment = new ContactFragment();

    loadFragment(homeFragment);

    bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {

            switch (menuItem.getItemId()) {

                case R.id.home:
                    //mManiNav.setItemBackgroundResource(R.color.blue);
                    loadFragment(homeFragment);
                    return true;

                case R.id.deposit:
                    // mManiNav.setItemBackgroundResource(R.color.colorAccent);
                    loadFragment(recipesFragment);
                    return true;

                case R.id.exchange:
                    //mManiNav.setItemBackgroundResource(R.color.colorPrimary);
                    loadFragment(knowledgeFragment);
                    return true;
                case R.id.profile:
                    // mManiNav.setItemBackgroundResource(R.color.light_blue);
                    loadFragment(aboutUsFragment);
                    return true;

                case R.id.payout:
                    // mManiNav.setItemBackgroundResource(R.color.light_blue);
                    loadFragment(contactFragment);
                    return true;



                default:
                    return false;

            }
        }
    });

}

这里是加载片段类:

 private void loadFragment(Fragment fragment) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.main_frame, fragment);
    transaction.addToBackStack(null);
    transaction.commit();
}

这是 popBackStackTillEntry 方法:

enter code here  public void popBackStackTillEntry(int entryIndex) {

    if (getSupportFragmentManager() == null) {
        return;
    }
    if (getSupportFragmentManager().getBackStackEntryCount() <= entryIndex) {
        return;
    }
    FragmentManager.BackStackEntry entry = getSupportFragmentManager().getBackStackEntryAt(
            entryIndex);
    if (entry != null) {
        getSupportFragmentManager().popBackStackImmediate(entry.getId(),
                FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }


}

这里是backpress方法:

boolean doubleBackToExitPressedOnce = false;
@Override
public void onBackPressed() {
    if (doubleBackToExitPressedOnce) {
        popBackStackTillEntry(0);
        moveTaskToBack(true);
        System.exit(0);
        return;
    }

    this.doubleBackToExitPressedOnce = true;
    loadFragment(new HomeFragment());

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            doubleBackToExitPressedOnce=false;
        }
    }, 2000);
}

答案 19 :(得分:-1)

这就是我解决我问题的方式

  1. WillPopScope()中包装主窗口小部件,并在onWillpop:中设置一个函数
Future<bool> _onBackpress() {
    if (_currentpage != 0) {
      setState(() {
        _currentpage--;//decreases number of pages till the fisrt page
      });
    } else {
    // a function to close the app
    }
  }