NeilLin
NeilLin

Reputation: 203

findviewbuid as T in kotlin

My kotlin extension

fun <T> View.findViewByIdCast(id : Int): T {
return findViewById(id) as T}

my viewholder

var llImage: LinearLayout = itemView.findViewByIdCast(R.id.llImg)

I use this fun to get all of view item in my project, but, in androidVersion 26 it show me "findviewbyid is not satisfied:inferred type T! is not a subtype of view" how could I Fix my extension fun in androidVersion 26?

Upvotes: 1

Views: 337

Answers (1)

zsmb13
zsmb13

Reputation: 89548

From API level 26, the findViewById methods themselves (the Java methods in AppCompatActivity, Fragment, View) are generic - you no longer need to wrap them. You can see usage examples in this answer.


If for some reason you'd still want to wrap it (say you're making a library and you need to keep your public API or something), you'd need to:

  • pass on the generic parameter
  • which means you could now avoid the cast
  • and finally, constraint T to satisfy the generic constraint on findViewById that its type parameter can only be a View

fun <T: View> View.findViewByIdCast(id: Int): T {
    return findViewById<T>(id)
}

Upvotes: 1

Related Questions