LoginSignup
5

More than 5 years have passed since last update.

Mortal で Activity を利用する場合の実装方法

Posted at

Mortal/Flow はライフサイクルを単純化し、とても良い設計を提供してくれます。

ただ、Mortal で実装されたView.getContext()ラップされていて Activity として利用することができません。

java.lang.ClassCastException: mortar.MortarContextWrapper cannot be cast to 
android.app.Activity

その場合、この Mortal のサンプルが参考になります。

以下の様に、Presenter を実装しこれを経由して Activity へアクセスします。

    class WindowOwner extends Presenter<WindowOwner.Activity> {

        interface Activity {
            void addFragsToWindow(int flags);
        }

        public static class Config() {
            final private int flags;
            Config(int flags) { this.flags = flags; }
            public int getFlags() { return this.flags; }
        }

        private Config config;

        public void setConfig(Config config) {
            this.config = config;
            update();
        }

        private void update() {
             WindowOwner.Activity activity = getView();
             if (activity != null) {
                  activity.addFlagsToWindow(config.getFlags());
             }
        }

        @dagger.Module(injects = {}, library = true)
        public static class WindowOwnerModule {
             @Provides
             @Singleton
             WindowOwner provideWindowOwnerPersenter() { return new WindowOwner(); }
        }
    }

上記で定義したWindowOwner.ModuleApplicationModule等のルートのModule へincludesしてください。

そして、Activity にWindowOwner.Activityのメソッドをオーバーライドします。

     class AwesomeActivity extends Activity implements WindowOwner.Activity {
          @Inject WindowOwner windowOwner;

          @Override
          protected void onCreate(Bundle savedInstanceState) {
              Mortar.inject(this, this);
              this.windowOwner.takeView(this);
          }

          @Override
          void addFragsToWindow(int flags) {
              getWindow().addFlags(flags);
          }
     }

これで、あなたの Screen で@Injectを行えば Activity にアクセスすることが出来るようになりました。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5