LoginSignup
49
27

More than 5 years have passed since last update.

AndroidOのfindViewByIdの仕様変更

Last updated at Posted at 2017-08-01

Google I/Oでは歓声が上がっていた(?)、Android OからのfindViewByIdの総称型対応について

findViewById

API Level 26からはfindViewByIdに総称型が追加されています。

Java

Javaではキャストする手間が減り記述量が減るようになりました。

image.png

バイトコード的には変更がないので、compileSdkVersionによって生成されるバイトコードは(恐らく)変化しません。

Kotlin

Kotlin 1.2からは問題なくコンパイルできるようになりました。
Information from explicit casts is used for type inference

1.2以前の記述
一方、KotlinではcompileSdkVersionを26に上げると、タイプパラメーターの推論ができないため、25までの記述はコンパイルエラーになります。

image.png

以下のように、タイプパラメーターを指定するか、推論できるようにすればコンパイルは通ります。

// こっちだとTextView!!になるので
val text26_1 = findViewById<TextView>(android.R.id.text2)
// 型を明示するほうが良さそう
val text26_2: TextView = findViewById(android.R.id.text2)

もしくは、予めfindViewByIdをラッピングする拡張を作っておくといいかもしれません。

// compileSdkVersion 25
@Suppress("UNCHECKED_CAST")
fun <V : View?> Activity.find(@IdRes id: Int): V = findViewById(id) as V
// compileSdkVersion 26
fun <V : View?> Activity.find(@IdRes id: Int): V = findViewById<V>(id)

ButterKnifeとか使っていれば恐らくこの問題は発生しないと思いますが、KotlinAndroiderはお気をつけください。

49
27
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
49
27