是否可以在全球范围内使用通用片段生成功能?

Is it possible to use common fragment generate function globally?

我有如下常见的片段生成函数:

// Common Fragment generation method
public void generateFragment(String speechString, String buttonString) {

    // Store data to be passed to the fragment in bundle format
    Bundle args = new Bundle();
    args.putString("Speech", speechString);
    args.putString("ButtonTitle", buttonString);

    // Instantiate Speech fragment and set arguments
    SpeechFragment newFragment = new SpeechFragment();
    newFragment.setArguments(args);

    // Dynamically add fragment to view using fragment transaction
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.fragment_container, newFragment);
    transaction.commit();
}

我在我的 activity 之一中多次使用此功能。现在,我发现这个函数可以和我的另一个 activity.
我也有全局变量 class 但它扩展了 Application.是的,我知道全局变量或全局函数应该在扩展应用程序 class.
的 class 中声明 所以我不能把函数包含 getSupportFragmentManager() 与 activity 连接作为全局函数。

有谁知道在activity之间使用这样的函数吗?

谢谢!

您可以将片段管理器传递到方法中:

public static void generateFragment(FragmentManager fragmentManager, String speechString, String buttonString)

我会避免像其他人建议的那样使用 BaseActivity,因为它限制了您可以扩展的内容:例如FragmentActivityActionBarActivityListActivityPreferenceActivity、e.t.c。 Google "composition over inheritance" 看看为什么这是一个糟糕的方法。

真的,您可能想要做的是拆分此方法。

在SpeechFragment.java中:

public static SpeechFragment newInstance(String speechString, String buttonString) {
    // Store data to be passed to the fragment in bundle format
    Bundle args = new Bundle();
    args.putString("Speech", speechString);
    args.putString("ButtonTitle", buttonString);

    // Instantiate Speech fragment and set arguments
    SpeechFragment newFragment = new SpeechFragment();
    newFragment.setArguments(args);
    return newFragment;
}

SpeechFragment class 然后将负责如何启动自己。 方法的其余部分

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, SpeechFragment.newInstance(speechString, buttonString);
transaction.commit();

然后可以只是使用此片段的 classes 的一部分。然后,您可以灵活地更改要使用的 FragmentManager 的容器 ID(可以改用 Fragment 的子 FragmentManager),添加/附加 e.t.c 而不是替换 - 取决于片段需要在activity.