Skip to content

Instantly share code, notes, and snippets.

@zsoltk
Created July 10, 2019 21:14
Show Gist options
  • Save zsoltk/477f73fcf79b7fdff27bd1ccbfe124b5 to your computer and use it in GitHub Desktop.
Save zsoltk/477f73fcf79b7fdff27bd1ccbfe124b5 to your computer and use it in GitHub Desktop.
class FooViewImpl @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0,
private val events: PublishRelay<Event> = PublishRelay.create<Event>()
) : LinearLayout(context, attrs, defStyle),
FooView,
// delegate implementing ObservableSource to our Relay
ObservableSource<Event> by events {
// 1. find the views
private val title: TextView by lazy { findViewById<TextView>(R.id.title)}
private val panel: ViewGroup by lazy { findViewById<ViewGroup>(R.id.panel)}
private val button: Button by lazy { findViewById<Button>(R.id.button)}
private val editText: EditText by lazy { findViewById<EditText>(R.id.editText)}
// 2. set listeners to trigger Events
override fun onFinishInflate() {
super.onFinishInflate()
button.setOnClickListener { events.accept(Event.ButtonClicked) }
editText.setOnFocusChangeListener { _, hasFocus -> events.accept(Event.TextFocusChanged(hasFocus)) }
}
// 3. render the ViewModel
override fun accept(vm: ViewModel) {
title.text = vm.title
panel.setBackgroundColor(ContextCompat.getColor(context, vm.bgColor))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment