Kotlin Android Extensions をFragmentで使ったときにNullPointerExceptionで落ちたのでその対処法メモです。
結論
onViewCreated()
を使う。
環境
kotlin 1.1.50
エラー内容
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
原因
textView
というIDのViewをkotlin-android-extensionsで参照した場合、内部的にはgetView().findViewById(R.id.textView)
を実行していて、FragmentのonCreateView()
ではgetView()
がnull
になるため。
サンプルコード
レイアウト
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
ダメな例
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater?.inflate(R.layout.fragment_main, container, false)
textView.text = "foo" // NullPointerException
return view
}
良い例
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater?.inflate(R.layout.fragment_main, container, false)
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
textView.text = "foo" // OK
}
補足
ActivityではonCreate()
で使っても大丈夫です。
参考
Kotlin Android Extensions - Kotlin Programming Language
https://kotlinlang.org/docs/tutorials/android-plugin.html
Kotlin Android Extensions and Fragments - Stack Overflow
https://stackoverflow.com/questions/34541650/kotlin-android-extensions-and-fragments