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


当前回答

如果你从父活动中获得Fragment的当前实例,你可以

findFragmentByID(R.id.container);

这实际上是视图中填充的fragment的当前实例。我也有同样的问题。我不得不加载相同的片段两次,保持一个备份。

下面的方法不起作用。它只是得到一个带有标签的片段。不要在这个方法上浪费时间。我相信它有它的用途,但获得同一片段的最新版本不是其中之一。

findFragmentByTag()

其他回答

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.

在这些情况下,使用事件总线(如Otto、EventBus或RxJava总线)特别方便。

虽然这种方法不一定会将当前可见的片段作为对象传递给您(尽管也可以这样做,但这会导致更长的调用链),但它允许您在当前可见的片段上执行操作(这通常是您想要知道当前可见的片段所做的事情)。

确保您尊重片段生命周期,并在适当的时间注册/取消注册事件总线 此时,您需要知道当前可见的片段并执行一组操作。使用事件总线输出事件。

所有已注册到总线的可见片段都将执行必要的操作。

受泰尼回答的启发,以下是我的观点。与大多数其他实现相比几乎没有修改。

private Fragment getCurrentFragment() {
    FragmentManager fragmentManager = myActivity.getSupportFragmentManager();
    int stackCount = fragmentManager.getBackStackEntryCount();
    if( fragmentManager.getFragments() != null ) return fragmentManager.getFragments().get( stackCount > 0 ? stackCount-1 : stackCount );
    else return null;
}

如果“myActivity”是您当前的活动,则将“myActivity”替换为“this”或使用对您的活动的引用。

final FragmentManager fm=this.getSupportFragmentManager();
final Fragment fragment=fm.findFragmentByTag("MY_FRAGMENT");

if(fragment != null && fragment.isVisible()){
      Log.i("TAG","my fragment is visible");
}
else{
      Log.i("TAG","my fragment is not visible");
}

我认为你们想知道u在哪个片段中 我想有一个解决办法,但我认为它不是最好的 但这是可行的 首先


你应该创建你的父片段,它扩展fragment


public class Fragment2 extends Fragment {
    private static position;
    public static int getPosition() {
        return position;
    }

    public static void setPosition(int position) {
        FragmentSecondParent.position = position;
    }
}

第二个

你应该在每个片段和每次写入onCreateView中扩展它

setPosition(//your fragmentposition here)

第三


你想在哪里得到当前的片段,你应该


写这篇文章

Fragment2 fragment= (Fragment2) getSupportFragmentManager()
    .findFragmentById(R.id.fragment_status);

int position = fragment.getPosition();
if(//position condition)
{
    //your code here
}