Created
December 14, 2018 18:49
-
-
Save afollestad/42d41598a2df05694023a6d1f4fd563c to your computer and use it in GitHub Desktop.
Create a lifecycle owner for a view without any boiler plate
This file contains 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
<?xml version="1.0" encoding="utf-8"?> | |
<resources> | |
<item format="integer" name="view_lifecycle_registry" type="id"/> | |
</resources> |
This file contains 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 android.view.View.OnAttachStateChangeListener | |
import androidx.lifecycle.LifecycleOwner | |
/** @author Aidan Follestad (@afollestad) */ | |
class ViewLifecycleOwner(view: View) : LifecycleOwner, OnAttachStateChangeListener { | |
private val lifecycle = SimpleLifecycle(this) | |
init { | |
view.addOnAttachStateChangeListener(this) | |
} | |
override fun getLifecycle() = lifecycle | |
override fun onViewAttachedToWindow(v: View?) = lifecycle.onCreate() | |
override fun onViewDetachedFromWindow(v: View) = lifecycle.onDestroy() | |
} | |
fun View.lifecycleOwner(): LifecycleOwner { | |
val tagOwner = getTag(R.id.view_lifecycle_registry) as? ViewLifecycleOwner | |
return if (tagOwner != null) { | |
tagOwner | |
} else { | |
val newOwner = ViewLifecycleOwner(this) | |
setTag(R.id.view_lifecycle_registry, newOwner) | |
newOwner | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment