Created
March 5, 2019 16:16
-
-
Save erdemtopak/ce5474bf2507ff7783dc2a31dcb665bc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.view.View | |
import androidx.fragment.app.Fragment | |
import androidx.lifecycle.Lifecycle | |
import androidx.lifecycle.LifecycleObserver | |
import androidx.lifecycle.OnLifecycleEvent | |
import java.lang.ref.WeakReference | |
import kotlin.properties.ReadOnlyProperty | |
import kotlin.reflect.KProperty | |
public fun <V : View> Fragment.bindView(id: Int): ReadOnlyProperty<Fragment, V> = ViewFinderProperty(id) | |
private class ViewFinderProperty<V : View>(val viewId: Int) : ReadOnlyProperty<Fragment, V> { | |
private var viewRef: V? = null | |
private var lifecycleObserver: LifecycleObserver? = null | |
override fun getValue(thisRef: Fragment, property: KProperty<*>): V { | |
return viewRef?.let { it } ?: findView(thisRef, viewId) | |
} | |
private fun findView(fragment: Fragment, id: Int): V { | |
attachLifecycleObserver(fragment) | |
return fragment.view!!.findViewById(id) | |
} | |
private fun attachLifecycleObserver(fragment: Fragment) { | |
if (lifecycleObserver == null) { | |
createLifecycleObserver().also { safeObserver -> | |
lifecycleObserver = safeObserver | |
fragment.lifecycle.addObserver(safeObserver) | |
} | |
} | |
} | |
private fun createLifecycleObserver() = object : LifecycleObserver { | |
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) | |
fun onDestroyView() { | |
viewRef = null | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment