项目作者: rjam

项目描述 :
CupHolder lets you retain Activity state on configuration changes, as you do on retained Fragments
高级语言: Java
项目地址: git://github.com/rjam/CupHolder.git
创建时间: 2017-01-23T19:06:21Z
项目社区:https://github.com/rjam/CupHolder

开源协议:

下载


CupHolder

CupHolder lets you easily retain Activity state on configuration changes, similarly to what you get when using retained Fragments. On MVP projects, this can be particularly useful to persist Presenters across orientation changes and other configuration changes.

Sure, show me the code

From the sample app:

  1. public class MainActivity extends HolderActivity<MainPresenter> {
  2. MainPresenter mPresenter;
  3. @Override
  4. public void onInitInstance(@Nullable MainPresenter instance) {
  5. if (instance != null) {
  6. // restore the retained presenter instance
  7. mPresenter = instance;
  8. } else {
  9. // nothing stored yet, create new presenter
  10. mPresenter = new MainPresenter(0);
  11. }
  12. }
  13. @Nullable
  14. @Override
  15. public MainPresenter onHoldInstance() {
  16. return mPresenter;
  17. }
  18. }

With the previous code, despite the activity being recreated when there’s a configuration change, mPresenter is retained and passed to the new activity on onInitInstance. Unlike onSaveInstanceState/onRestoreInstanceState, this allows you to save actual objects without requiring you to move them onto a Bundle but beware that, like retained fragments, CupHolder will not retain your data across Activity restarts, only configuration changes! So, don’t forget to properly implement onSaveInstanceState/onRestoreInstanceState as well :)

Ok, but how does it work?

At its core the library acts simply as a wrapper for the lesser known onRetainNonConfigurationInstance) / onRetainCustomNonConfigurationInstance) which have always been part of the Activity lifecycle, while providing friendly default implementations for both Activity and AppCompatActivity.

Sample Projects

Sample

In the sample app you can quickly verify that the model’s state (the displayed number) is being kept across screen rotations. A second activity shows the same behavior but using a regular retained fragment for comparison.

Sample-MVP

A similar project showcasing how the library can be used to easily retain Presenters during configuration changes.

Dependency

Available through jitpack: https://jitpack.io/#rjam/CupHolder

Step 1. Add the JitPack repository to your build file:

  1. allprojects {
  2. repositories {
  3. ...
  4. maven { url 'https://jitpack.io' }
  5. }
  6. }

Step 2. Add the dependency

  1. dependencies {
  2. compile 'com.github.rjam:CupHolder:<latest-release>'
  3. }