Austyn Mahoney Austyn Mahoney - 1 month ago 13
Android Question

How to implement a backstack when using the KitKat Transitions Framework

I am using the new KitKat Transitions API on Android. I have created two

Scene
objects using two layouts. I animate from
Scene 1
to
Scene 2
inside a
Fragment
. I want to automatically move back to the previous
Scene
when the user presses the back button.

Is there some kind of built-in backstack mechanism when using
Transitions
, or do I have to roll my own?

It is easy enough to call
TransitionManager.go(scene1)
, but I really do not want to implement an
onBackPressed()
listener in all my fragments that have
Scene
animations.

Answer

I ended up rolling my own solution.

Have your Activity implement this

public interface SceneBackstackHandler {

    public void addBackstackListener(BackstackListener listener);

    public void removeBackstackListener(BackstackListener listener);

    public void removeAllBackstackListeners();

    public interface BackstackListener {
        public boolean onBackPressed();
    }
}

Activity

private final Object mBackstackListenerLock = new Object();
private List<BackstackListener> mBackstackListeners = new ArrayList<>();

@Override
public void onBackPressed() {
    synchronized (mBackstackListenerLock) {
        for (BackstackListener mBackstackListener : mBackstackListeners) {
            if (mBackstackListener.onBackPressed()) {
                // handled by fragment
                return;
            }
        }
        super.onBackPressed();
    }
}

@Override
protected void onPause() {
    super.onPause();
    removeAllBackstackListeners();
}

@Override
public void addBackstackListener(BackstackListener listener) {
    synchronized (mBackstackListenerLock) {
        mBackstackListeners.add(listener);
    }
}

@Override
public void removeBackstackListener(BackstackListener listener) {
    synchronized (mBackstackListenerLock) {
        mBackstackListeners.remove(listener);
    }
}

@Override
public void removeAllBackstackListeners() {
    synchronized (mBackstackListenerLock) {
        mBackstackListeners.clear();
    }
}

Child Fragment:

public class MySceneFragment extends Fragment
        implements SceneBackstackHandler.BackstackListener {

    private Scene mCurrentScene;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mBackstackHandler = (SceneBackstackHandler) activity;
        mBackstackHandler.addBackstackListener(this);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mBackstackHandler.removeBackstackListener(this);
    }

    @Override
    public boolean onBackPressed() {
        if (mCurrentScene != null && mCurrentScene.equals(mMyScene)) {
            removeMyScene();
            return true;
        }
        return false;
    }

    private void changeScene(Scene scene) {
        TransitionManager.go(scene);
        mCurrentScene = scene;
    }
}