我在Android中玩碎片。

我知道我可以通过使用以下代码更改一个片段:

FragmentManager fragMgr = getSupportFragmentManager();
FragmentTransaction fragTrans = fragMgr.beginTransaction();

MyFragment myFragment = new MyFragment(); //my custom fragment

fragTrans.replace(android.R.id.content, myFragment);
fragTrans.addToBackStack(null);
fragTrans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragTrans.commit();

我的问题是,在Java文件中,如何获得当前显示的片段实例?


当前回答

以下是我的解决方案,我发现它适用于低片段场景

public Fragment getVisibleFragment(){
    FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
    List<Fragment> fragments = fragmentManager.getFragments();
    if(fragments != null){
        for(Fragment fragment : fragments){
            if(fragment != null && fragment.isVisible())
                return fragment;
        }
    }
    return null;
}

其他回答

这是最好的方法:

       android.app.Fragment currentFragment=getFragmentManager().findFragmentById(R.id.main_container);
            if(currentFragment!=null)
            {
                String[] currentFragmentName = currentFragment.toString().split("\\{");
                if (currentFragmentName[0].toString().equalsIgnoreCase("HomeSubjectFragment"))
                {
                    fragment = new HomeStagesFragment();
                    tx = getSupportFragmentManager().beginTransaction();
                    tx.replace(R.id.main_container, fragment);
                    tx.addToBackStack(null);
                    tx.commit();
                }
                else if(currentFragmentName[0].toString().equalsIgnoreCase("HomeStagesFragment"))
                {
                    new AlertDialog.Builder(this)
                            .setMessage("Are you sure you want to exit?")
                            .setCancelable(false)
                            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    finish();
                                }
                            })
                            .setNegativeButton("No", null)
                            .show();
                }

            }

不要忘记在header中定义这个:

private Fragment fragment;
FragmentTransaction tx;

我遇到了一个类似的问题,我想知道当返回键被按下时最后显示的片段是什么。我用了一个非常简单的方法。每次我打开一个片段,在onCreate()方法中,我在我的单例中设置了一个变量(用你的片段的名称替换“myFragment”)

MySingleton.currentFragment = myFragment.class;

变量在单例中声明为

public static Class currentFragment = null; 

然后在onBackPressed()中检查

    if (MySingleton.currentFragment == myFragment.class){
        // do something
        return;
    }
    super.onBackPressed();

确保调用super.onBackPressed();在“返回”之后,否则应用程序将处理返回键,这在我的情况下导致应用程序终止。

我发现findFragmentByTag不是那么方便。如果你在你的Activity或父Fragment中有字符串currentFragmentTag,你需要将它保存在onSaveInstanceState中并在onCreate中恢复。即使你这样做,当Activity重新创建时,onAttachFragment将在onCreate之前调用,所以你不能在onAttachFragment中使用currentFragmentTag(例如。更新一些基于currentFragmentTag的视图),因为它可能还没有恢复。

我使用以下代码:

Fragment getCurrentFragment() {
    List<Fragment> fragments = getSupportFragmentManager().getFragments();
    if(fragments.isEmpty()) {
        return null;
    }
    return fragments.get(fragments.size()-1);
}

FragmentManager的文档中指出

列表中片段的顺序是它们被添加或附加的顺序。

当你需要做基于当前片段类型的事情时,只需使用MyFragment的getCurrentFragment()实例而不是currentFragmentTag.equals("my_fragment_tag")。

注意,onAttachFragment中的getCurrentFragment()不会得到附加的片段,而是之前附加的片段。

芬兰湾的科特林;

val currentFragment = supportFragmentManager.fragments.last()

In the main activity, the onAttachFragment(Fragment fragment) method is called when a new fragment is attached to the activity. In this method, you can get the instance of the current fragment. However, the onAttachFragment(Fragment fragment) method is not called when a fragment is popped off the back stack, ie, when the back button is pressed to get the top fragment on top of the stack. I am still looking for a callback method that is triggered in the main activity when a fragment becomes visible inside the activity.