7
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Ionic4,Ionic5でのAndroidの戻るボタンの無効化、およびカスタムイベントの設定

Posted at

AndroidにはiPhoneにはない物理的な戻るボタンが存在します。
本記事ではIonicプロジェクトでこの戻るボタンを無効化する方法をまとめます。

Ionic3以前

Ionic3の環境で試していないですがPlatformregisterBackButtonActionメソッドを使用することで制御できるようです。

Ionic4からregisterBackButtonActionが使えない問題

Ionic3のPlatformにあったregisterBackButtonActionメソッドがないので、Androidの戻るボタンを上書きすることができません。
移行のドキュメントに記載が見当たりませんでしたが、3から4以降へバージョンアップする際にソースコードを修正する必要があります。

ここら辺の話がIonic4betaのissuesに挙がっています。
GitHub - When platform hardware backButton subscribed, router.goBack should not be triggered

このissuesに対応するためsubscribeWithPriority が実装されています。Androidの戻るボタンの制御の問題はこのメソッドを使用することで解決できます。
GitHub - feat(angular): observer based api to override hardware back button

subscribeWithPriorityの利用方法

アプリ全体で戻るボタンを制御したい場合

ルートコンポーネントで戻るボタンをオーバーライドするだけで、戻るボタンが無効化されます。

app.component.ts
this.platform.ready().then(() => {
  this.platform.backButton.subscribeWithPriority(
    10000,
    () => {
      // something...
    }
  );  
});

一部のページで戻るボタンを制御したい場合

一部のページで戻るボタンをオーバライドする場合はページコンポーネントのライフサイクルの入口でオーバーライドし、出口で解除を行います。
アプリに適切なライフサイクルイベントで解除を行なってください。

sample-page.ts
import { Subscription } from 'rxjs';

export class SpeakerDetailPage {
  backButtonSubscription: Subscription;

  ngOnInit() {
    this.backButtonSubscription = this.platform.backButton.subscribeWithPriority(
      10000,
      () => {
        // something...
      }
    );
  }
  ngOnDestroy() {
    this.backButtonSubscription.unsubscribe(); // subscribeWithPriorityを解除
  }
}
7
0
0

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
7
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?