4
4

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 5 years have passed since last update.

FragmentのonAttach()はAPIレベルによって使い分けよう

Posted at

タイトルが全てですが、onAttach()はAPIレベルが23以上、以下で動く・動かないが変わるようです。

今回記載していたコードは下記でした。

private var listner: onDateSelectListnerIn? = null

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        if (context is onDateSelectListnerIn) {
            listner = context
        }
    }

DatePicker表示用に作ったフラグメントのonAttach()です。
試していたら、後続の処理でlistnerがNullでエラーが発生していました。

デバックしてみるとそもそもonAttach()を通らないことがわかり、いろいろ調べてみました。

なんと、上記のコードはAPIレベルが23以上じゃないと動かないコードでした・・・

APIレベル23以下だと下記のような処理を行っていて、23以上では非推奨となっていました。

override fun onAttach(activity: Activity?) {
        super.onAttach(activity)
        if (activity is onDateSelectListnerIn) {
            listner = activity
        }
    }

なので、下記のようにバージョンで条件分岐を行いました。

override fun onAttach(activity: Activity?) {
        super.onAttach(activity)
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) return
        if (activity is onDateSelectListnerIn) {
            listner = activity
        }
    }

こうすると23以下でも引数のactivityからlistnerを取得できるようになり、エラーは解消されました。

Androidに限らず、iOSでもバージョン問題は起こりえることだと思います。
困ったら、リファレンスを確認するしか方法がない気がします。
他にいい方法があれば知りたいです。

参照

リファレンス
https://developer.android.com/reference/android/app/DialogFragment

4
4
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?