Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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でインスタンスを取得できました!ありがたや~

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

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away