片段不能启动,必须将它们添加到容器中。
片段并不是要独立运作,他们需要一个封闭的活动。
具有以下布局:
[...]
<FrameLayout android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?android:attr/detailsElementBackground" />
[...]
您将片段像这样:
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, newFragment);
transaction.commit();
您可以通过使用捆绑并创建片段参数传递给片段如下:
TestFragment newFragment = new TestFragment();
Bundle args = new Bundle();
args.putString("Hello world!");
newFragment.setArguments(args);
这必须在交易之前完成。
如需进一步信息请参考上编辑代码official documentation
注意:您必须从活动中的FrameLayout是一部分内部调用事务。
或者使用比较脏的解决方法: 在主营:
public class Main extends Activity{
public static Main currentInstance;
public void onCreate(Bundle boomerang){
currentInstance = this;
}
}
播放列表中的活动,然后使用Main.currentInstance.getSupportFragmentManager()
等
但我不会推荐它。
我已经编辑我的代码。但正如在那里提到的,我不会尝试从另一个活动中替换片段。 – Ch4t4r