按下后退按钮时如何获取最后使用的片段 [英] How to get last Fragment used when pressing back button

查看:94
本文介绍了按下后退按钮时如何获取最后使用的片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下代码的简单片段:

I have a simple fragment with this code:

private BottomNavigationView.OnNavigationItemSelectedListener navListener =
            new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                    Fragment selectedFragment= null;

                    switch (menuItem.getItemId()){
                        case R.id.nav_home:
                            selectedFragment= new HomeFragment();
                            setTitle("Beranda");
                            break;
                        case R.id.nav_message:
                            selectedFragment= new MessageFragment();
                            setTitle("Pesan");
                            break;
                        case R.id.nav_transaction:
                            selectedFragment= new TransactionFragment();
                            setTitle("Transaksi");
                            break;
                        case R.id.nav_profile:
                            selectedFragment= new ProfileFragment();
                            setTitle("Profil");
                            if(sessionLevel.equals("admin")){
                                setTitle("Admin");
                            }
                            break;
                    }
                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
                    return true;
                }
            };

大多数片段只是意图活动的某种持有者.而且Activity本身没有花哨的代码.

Most of the fragment are just some kind of holder for Intent Activity. And the Activity itself doesnt have some fancy code.

问题在于,当我在配置文件"菜单上执行意图"然后按回去时,显示的片段是 HomeActivity ,但是所选的按钮是 Profile .我不知道其他两个片段,因为我还没有,但可能他们做的是同一件事.

The problem is that when i do Intent on Profile menu and then press back, the fragment shown is HomeActivity but the selected button is Profile. I dont know about the other 2 fragment since im not there yet, but probably they do the same thing.

推荐答案

  1. 创建界面:

public interface IOnBackPressed {
    boolean onBackPressed();
}

  1. 在Fragment中实现IOnBackPressed,例如:

public class FAQFragment extends Fragment implements IOnBackPressed {
    public boolean onBackPressed() {
        return false
    }
}

  1. 在主活动Backpress上使用

@Override
public void onBackPressed(){
     if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
          getSupportFragmentManager().popBackStack();
     } 
}

这篇关于按下后退按钮时如何获取最后使用的片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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