Android 如何通过单击按钮继续到下一个片段

Android 如何通过单击按钮继续到下一个片段,android,android-fragments,Android,Android Fragments,我在考虑做一些类似的事情,但恰恰相反。假设我在父活动的操作栏中有一个“继续”按钮。我有几个片段应该按顺序显示。如何通过单击continue按钮转到下一个片段?使用continue按钮的OnClick,只需将新片段替换或添加到容器中即可 在Onclick的Continue按钮Do nested if else或switch中: Fragment f = getActivity().getFragmentManager().findFragmentById(R.id.fragment_contain

我在考虑做一些类似的事情,但恰恰相反。假设我在父活动的操作栏中有一个“继续”按钮。我有几个片段应该按顺序显示。如何通过单击continue按钮转到下一个片段?

使用continue按钮的
OnClick
,只需将新片段替换或添加到
容器中即可

Onclick
Continue按钮Do nested if else或switch中:

Fragment f = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
if (f instanceof FirstFFragmentClass) {
// do something with f
    FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
    SecondFragmentClass secondFragment = new SecondFragmentClass();
    ft.replace(R.id.fragment_container, secondFragment);

} else if (f instanceof SecondFragmentClass){

}

从主活动调用一个方法,该方法执行以下操作:

Fragment myNewFragment = MyFragmentClass.newInstance();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, myNewFragment, "newTag");
transaction.addToBackStack(null);
transaction.commit();

其中R.id.fragment\u容器可能是XML中的FrameLayout或其他布局,myNewFragment是通过创建新的fragment对象或newInstance()之类的自定义方法返回的片段,您可以传递参数以使用相同的fragment类,但布局不同的视图/文本。

将新片段添加到backstack。@Kimkvin,谢谢,但你能详细说明一下吗?我正在考虑创建一个可以在父活动的continue按钮的onClickListener中调用的方法。这就是我应该将新片段添加到backstack的地方吗?setOnClickListener添加到父活动中的视图中,然后您可以添加任何想要的片段。显示您的代码。谢谢。我想知道当我在实际活动中时,是否仍然需要
getActivity()
?如果你在实际活动中,那么你可以避免
getActivity()