我在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文件中,如何获得当前显示的片段实例?


当前回答

如果您正在使用Jetpack导航库:

val currentFragment = defaultNavigator.currentDestination

其他回答

在你的活动中,在创建之前初始化你的片段

    MyFragment myFragment = new MyFragment(); // add this
 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
........

然后调用该方法来查看您的片段

openFragment(this.myFragment);

这是方法

(R.id.frame_container)是xml文件中的片段容器id (框架布局)

 private void openFragment(final Fragment fragment)   {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.frame_container, fragment);
        transaction.commit();

    }

那么在你的活动中,Override方法应该是这样的

    public void onBackPressed() {
            if (myFragment.isVisible()) {
                myFragment.onBackPressed(this);
                return;
            }
            super.onBackPressed();
        }

然后在你的片段中放入这个方法

public  void onBackPressed(Activity activity) {
    Toast.makeText(activity, "Back Pressed inside Fragment", Toast.LENGTH_SHORT).show();
}

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.

这样比暴露在这里更安全

supportFragmentManager.fragments.lastOrNull()?.let { currentFragment ->
               
      //Do something here
 }

嗯,这个问题得到了很多观点和关注,但仍然没有得到遏制 从我的端最简单的解决方案-使用getFragments()。

            List fragments = getSupportFragmentManager().getFragments();
            mCurrentFragment = fragments.get(fragments.size() - 1);

如果您正在使用Jetpack导航库:

val currentFragment = defaultNavigator.currentDestination