Skip to content

Instantly share code, notes, and snippets.

@guuilp
Last active January 19, 2019 15:30
Show Gist options
  • Save guuilp/f01e8b171d973303ba38796e9812ea38 to your computer and use it in GitHub Desktop.
Save guuilp/f01e8b171d973303ba38796e9812ea38 to your computer and use it in GitHub Desktop.
class PeopleActivity : AppCompatActivity() {
private val people = listOf(
Person(1, "Person 1", "Brazil"),
Person(2, "Person 2", "USA"),
Person(3, "Person 3", "Canada"),
Person(4, "Person 4", "Russia"),
Person(5, "Person 5", "Germany")
)
private lateinit var viewModel: PeopleViewModel
private lateinit var adapter: PeopleAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_people)
initComponents()
observeChanges()
}
private fun initComponents() {
viewModel = ViewModelProviders.of(this).get(PeopleViewModel::class.java)
adapter = PeopleAdapter(people, AdapterListener())
adapter.setHasStableIds(true)
list.adapter = adapter
button.setOnClickListener {
val person = viewModel.getSelectedPerson().value
if (person != null) {
Toast.makeText(this, person.name, Toast.LENGTH_LONG).show()
} else {
Toast.makeText(this, "You need to select someone", Toast.LENGTH_LONG).show()
}
}
}
private fun observeChanges() {
viewModel.getSelectedPerson().observe(this, Observer {
adapter.updateSelectedPerson(it)
})
}
private inner class AdapterListener : PeopleAdapter.Listener {
override fun onItemClicked(person: Person) {
viewModel.setSelectedPerson(person)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment