26
11

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.

Kotlinでkotlin-android-extensionsをFragmentでも使いたい

Last updated at Posted at 2016-05-18

#kotlin-android-extensions

KotlinでAndroidアプリ書いているとき、layoutファイルに

<TextView
    android:id="@+id/textview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

こんなん書いてたとしたら、このPlugin利用するとActivity中に

override fun onCreate(savedInstanceState: Bundle?) {
    setContentView(R.layout.activity_main)
    textview.text = "hogehoge"
}

とidが変数名となって利用できますよね?とても便利です

#Fragmentでの利用

このkotlin-android-extensionsFragmentでもつかいたいなぁと思った時、最初こう書きました

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    val view = inflater!!.inflate(R.layout.fragment_main, container, false)
    textview.text = "hogehoge"
    return view
}

コンパイルは通りましたが、実行したらNullPointerExceptionで落ちました…

これはまたview.findViewById(ResourceID)の嵐かと思いましたが、調べたらありました!

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    val view = inflater!!.inflate(R.layout.fragment_main, container, false)
    return view
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
    textview.text = "hogehoge"
}

onViewCreatedでインスタンスを取得できました!ありがたや~

参考までに書いてみました丿

26
11
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
26
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?