1/* 2 * Copyright 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package androidx.fragment.app; 18 19import android.os.Bundle; 20 21public class ReentrantFragment extends StrictFragment { 22 private static final String FROM_STATE = "fromState"; 23 private static final String TO_STATE = "toState"; 24 int mFromState = 0; 25 int mToState = 0; 26 boolean mIsRestored; 27 28 public static ReentrantFragment create(int fromState, int toState) { 29 ReentrantFragment fragment = new ReentrantFragment(); 30 fragment.mFromState = fromState; 31 fragment.mToState = toState; 32 fragment.mIsRestored = false; 33 return fragment; 34 } 35 36 @Override 37 public void onStateChanged(int fromState) { 38 super.onStateChanged(fromState); 39 // We execute the transaction when shutting down or after restoring 40 if (fromState == mFromState && mState == mToState 41 && (mToState < mFromState || mIsRestored)) { 42 executeTransaction(); 43 } 44 } 45 46 private void executeTransaction() { 47 getFragmentManager().beginTransaction() 48 .add(new StrictFragment(), "should throw") 49 .commitNow(); 50 } 51 52 @Override 53 public void onSaveInstanceState(Bundle outState) { 54 super.onSaveInstanceState(outState); 55 outState.putInt(FROM_STATE, mFromState); 56 outState.putInt(TO_STATE, mToState); 57 } 58 59 @Override 60 public void onCreate(Bundle savedInstanceState) { 61 if (savedInstanceState != null) { 62 mFromState = savedInstanceState.getInt(FROM_STATE); 63 mToState = savedInstanceState.getInt(TO_STATE); 64 mIsRestored = true; 65 } 66 super.onCreate(savedInstanceState); 67 } 68} 69 70