Skip to content

Instantly share code, notes, and snippets.

@aoriani
Created March 29, 2018 20:26
Show Gist options
  • Save aoriani/eb06b9efd477c9493f4bd46e3508d5d1 to your computer and use it in GitHub Desktop.
Save aoriani/eb06b9efd477c9493f4bd46e3508d5d1 to your computer and use it in GitHub Desktop.
A simple implementation of ButterKnife in Kotlin using reflection
package io.aoriani.simplebutterknife
import android.os.Bundle
import android.support.annotation.IdRes
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.Button
import android.widget.TextView
import kotlin.reflect.KMutableProperty1
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.jvm.isAccessible
@Target(AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class IdForView(@IdRes val id: Int)
class MainActivity : AppCompatActivity() {
@IdForView(R.id.textView)
private lateinit var textView: TextView
@IdForView(R.id.button)
private lateinit var button: Button
private var counter = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bind(this)
button.setOnClickListener { textView.text = (++counter).toString() }
}
}
fun bind(activity: AppCompatActivity) {
activity::class.declaredMemberProperties.asSequence()
.filter { it is KMutableProperty1 && it.annotations.any { it is IdForView } }
.forEach {
val viewId = it.findAnnotation<IdForView>()?.id!! // It cannot be null due above check
val view = activity.findViewById<View>(viewId)
it as KMutableProperty1<AppCompatActivity, View>
it.isAccessible = true
it.set(activity, view)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment