我已经看到了在应用程序中实例化一个新Fragment的两个通用实践:

Fragment newFragment = new MyFragment();

and

Fragment newFragment = MyFragment.newInstance();

第二个选项使用静态方法newInstance(),通常包含以下方法。

public static Fragment newInstance() 
{
    MyFragment myFragment = new MyFragment();
    return myFragment;
}

起初,我认为主要的好处是,我可以重载newInstance()方法,以便在创建新的Fragment实例时提供灵活性——但我也可以通过为Fragment创建重载构造函数来实现这一点。

我错过什么了吗?

一种方法相对于另一种方法有什么好处?还是说这只是一个很好的练习?


当前回答

还有另一种方法:

Fragment.instantiate(context, MyFragment.class.getName(), myBundle)

其他回答

还有另一种方法:

Fragment.instantiate(context, MyFragment.class.getName(), myBundle)

实例化片段的最好方法是使用默认的片段。实例化方法或创建工厂方法来实例化片段 注意:总是在片段中创建一个空构造函数,而在恢复片段内存时会抛出运行时异常。

我最近在这里。但我知道的一些事也许能帮到你。

如果您正在使用Java,那么没有什么需要更改的。但是对于Kotlin开发人员来说,下面是一些代码片段,我认为它们可以让你成为一个运行的基础:

父母片段:

inline fun <reified T : SampleFragment> newInstance(text: String): T {
    return T::class.java.newInstance().apply {
        arguments = Bundle().also { it.putString("key_text_arg", text) }
    }
}

正常调用

val f: SampleFragment = SampleFragment.newInstance("ABC")
// or val f = SampleFragment.newInstance<SampleFragment>("ABC")

你可以在子fragment类中扩展父init操作:

fun newInstance(): ChildSampleFragment {
    val child = UserProfileFragment.newInstance<ChildSampleFragment>("XYZ")
    // Do anything with the current initialized args bundle here
    // with child.arguments = ....
    return child
}

快乐的编码。

我相信我有一个更简单的解决方案。

public class MyFragment extends Fragment{

   private String mTitle;
   private List<MyObject> mObjects;

   public static MyFragment newInstance(String title, List<MyObject> objects)
   MyFragment myFrag = new MyFragment();
   myFrag.mTitle = title;
   myFrag.mObjects = objects;
   return myFrag;
   }

使用此代码100%修复您的问题

在firstFragment中输入这个代码

public static yourNameParentFragment newInstance() {

    Bundle args = new Bundle();
    args.putBoolean("yourKey",yourValue);
    YourFragment fragment = new YourFragment();
    fragment.setArguments(args);
    return fragment;
}

这个示例发送布尔数据

和在SecendFragment

yourNameParentFragment name =yourNameParentFragment.newInstance();
   Bundle bundle;
   bundle=sellDiamondFragments2.getArguments();
  boolean a= bundle.getBoolean("yourKey");

必须值在第一个片段是静态的

快乐的代码