Skip to content

Instantly share code, notes, and snippets.

@Tagakov
Last active May 31, 2017 20:04
Show Gist options
  • Save Tagakov/30e58bd397e709eaecb2af81353cd1ff to your computer and use it in GitHub Desktop.
Save Tagakov/30e58bd397e709eaecb2af81353cd1ff to your computer and use it in GitHub Desktop.
To reproduce bug:1. open app, 2. click on fullscreen button3. rotate device twice4. click back twice (exit app)5. look at logcat
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new FrameLayout(this) {{
setId(42);
}});
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(42, new Master())
.commit();
}
}
public static class Master extends Fragment {
Holder h;
@Override
public void onCreate(@Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
Log.d("TAG", "create");
getChildFragmentManager()
.beginTransaction()
.add(h = new Holder(), "holder")
.commit();
} else {
h = (Holder) getChildFragmentManager().findFragmentByTag("holder");
}
}
@Nullable
@Override
public View onCreateView(final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable final Bundle savedInstanceState) {
return new Button(container.getContext()) {{
setText("NEXT");
}};
}
@Override
public void onViewCreated(final View view, @Nullable final Bundle savedInstanceState) {
h.listener = integer -> ((Button) view).setText("" + integer);
view.setOnClickListener(v ->
getFragmentManager()
.beginTransaction()
.replace(42, new Master())
.addToBackStack(null)
.commit());
}
@Override
public void onDestroyView() {
super.onDestroyView();
h.listener = null;
}
}
public static class Holder extends Fragment {
interface Listener {
void call(int i);
}
private int i;
private final Handler handler = new Handler();
public Holder() {
Log.d("TAG", "constuctor");
setRetainInstance(true);
}
Listener listener;
@Override
public void onCreate(@Nullable final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
i = savedInstanceState.getInt("me");
}
notifyListeners(i);
}
@Override
public void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
Log.d("TAG", "save" + this);
outState.putInt("me", i);
}
@Override
public void onDestroy() {
handler.removeCallbacksAndMessages(null);
Log.d("TAG", "dest" + this);
super.onDestroy();
}
private void notifyListeners(final int i) {
this.i = i;
Log.d("TAG", "" + this + " counter " + i + "");
if (listener != null) {
listener.call(i);
}
handler.postDelayed(() -> notifyListeners(i + 1), 1000);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment