1

我有一个 MainActivity,它有一个包含主机片段的 viewpager(可以包含其他带有子片段管理器的片段)。我想要实现的是在单击通知上的操作时从其中一个子片段开始一个对话框片段。我正在使用 FCM 并且通知正在正确发出,但是当我尝试添加子片段时,我在尝试获取子片段管理器时得到Fragment not attach to activity

@Override
    protected void onCreate(Bundle savedInstanceState) {
        addFrags();//adding fragments to the viewpager
        Bundle bundle = getIntent().getExtras();
        if (bundle.containsKey(ARG_ACTION_ID)) {
            mAction = (Action) bundle.getSerializable(ARG_ACTION_ID);
        }
}

@Override
    protected void onStart() {
        super.onStart();
        switch (mAction) {
            case EDIT_TFR: {
                mViewPager.setCurrentItem(2);//this much is happening, it will go to the 3rd page of viewpager if i didnt do the rest.
                onFragmentInteraction(id);
                break;
            }
        }
}
// this is an interface i use to interact with the acticity from my child fragment, which is also the one i am calling from onstart
@Override
public void onFragmentInteraction(String id) {
    HostFragment hostFragment = (HostFragment) mPagerAdapter.getItem(2);
    Fragment contentfragment = NewFrag.newInstance(id);
    hostFragment.addFragment(contentFragment, true);
}

这是 HostFragment 中的 addFragent 方法

public void addFragment(Fragment fragment, boolean addToBackstack) {
    FragmentManager fm = this.getChildFragmentManager(); //this is were i am getting the error
    FragmentTransaction fragmentTransaction = fm.beginTransaction();
    fragmentTransaction.add(id.hosted_fragment, fragment);
    if (addToBackstack) {
        fragmentTransaction.addToBackStack((String)null);
    }

    fragmentTransaction.commit();
    fm.executePendingTransactions();
}

我的计划是在 NewFrag 中调用一个公共方法,该方法将打开 dialogfrag。

我知道此时可能不会附加该片段。请让我知道如何实现这一目标。

4

0 回答 0