5
1

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 1 year has passed since last update.

Android Studio Electric EelでviewModels()やonBackPressedDispatcherが認識されない問題の解決方法

Posted at

概要

AppCompatActivity(ComponentActivity)を継承していてもIDE上で以下のエラーが出てしまう対処方法です。
(動くけど、IDE上で赤くなる事象です)

スクリーンショット 2023-03-10 12.48.57.png

以前のバージョンでも以下のような問題がありましたが同じようにやれば良いです。
https://qiita.com/ko2ic/items/dce06a03131268d1d6c3

解決方法

ワークアランドとして、こんな拡張メソッドを用意し利用しておけば良いでしょう。ASのバグが直ったら、この処理を削除します。
当然、ComponentActivityを継承してない場合に利用すると落ちますので、気をつけましょう。

inline fun <reified VM : ViewModel> Activity.viewModels(
    noinline extrasProducer: (() -> CreationExtras)? = null,
    noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null,
) = (this as ComponentActivity).viewModels<VM>(extrasProducer, factoryProducer)

val Activity.onBackPressedDispatcher: OnBackPressedDispatcher
    get() = (this as ComponentActivity).onBackPressedDispatcher
5
1
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
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?