Android support library 27, Fragment update?

后端 未结 1 647
萌比男神i
萌比男神i 2020-12-09 10:12

Since I updated my project to SDK version 27 and gradle plugins for the support library to version 27.0.0 I needed to change my code.

With 26.1.0<

1条回答
  •  醉梦人生
    2020-12-09 10:30

    These were deliberate changes. Before this version of the support library, these classes had no nullability annotations, so from Kotlin, all these types were just platform types. In 27, they added the necessary annotations, so now these types are definitely marked as either nullable or non-nullable in Kotlin - there's no need to guess whether they can be null.

    As for the specific methods you've mentioned:

    • The getActivity and getContext methods return nullable types because when the Fragment is not attached to an Activity, these methods already returned null. There's no change in behaviour, it's just explicitly marked now, so you can safely handle it.
    • The inflater parameter of the onCreateView method used to be a platform type, so it was up to you whether you marked it nullable or not. Since it will never be called with null, it has been explicitly annotated as @NonNull, so its type in Kotlin now is strictly LayoutInflater instead of the "looser" LayoutInflater! type.

    Edit: starting from support library 27.1.0, you can use the requireActivity and requireContext methods, which return non-nullable types, with the caveat that they'll throw an IllegalStateException when the regular methods would return null.

    0 讨论(0)
提交回复
热议问题