У меня есть основной вид деятельности, который будет содержать много фрагментов. Предположим, на данный момент 2 действия A и B Вот код
Введение Упражнение
public class introductionActivity extends AppCompatActivity implements View.OnClickListener {
private static String TAG = "MyActivity";
private static Fragment fragment ;
public static android.support.v4.app.FragmentManager fragmentManager;
public static android.support.v4.app.FragmentTransaction fragmentTransaction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_introduction);
if(savedInstanceState != null){
fragment = getSupportFragmentManager().getFragment(savedInstanceState, "MyFragment");
}
fragment = new intro1();
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
ActionBar actionbar = getSupportActionBar();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, " MyFragment", fragment);
}
@Override
public void onClick(View v) {
}
public static void doStuff(){
fragment = new intro2();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
}
Вступительное действие (MainActivity) содержит FrameLayout, который будет заменен первым фрагментом.
Фрагмент 1
public class intro1 extends Fragment{
private View rootView;
public static Activity intro1Activity;
public Button intro1nxtButton;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_intro_1, container, false);
intro1nxtButton = (Button)rootView.findViewById(R.id.intro1Next_button);
intro1nxtButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
introductionActivity.doStuff();
}
});
// Inflate the layout for this fragment
return rootView;
}
}
Первый фрагмент содержит кнопку, и после ее нажатия фрагмент заменяется фрагментом 2
Фрагмент 2
public class intro2 extends Fragment {
private View rootView;
public static Activity intro2Activity;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_intro_2, container, false);
// Inflate the layout for this fragment
return rootView;
}
}
Что я хочу, так это когда я нажимаю кнопку «Назад» или закрываю вводное действие и снова открываю его, он должен восстановить фрагмент 2, а не фрагмент 1