in People/app/src/main/java/com/example/android/people/ui/chat/ChatFragment.kt [71:146]
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val id = arguments?.getLong(ARG_ID)
if (id == null) {
parentFragmentManager.popBackStack()
return
}
val prepopulateText = arguments?.getString(ARG_PREPOPULATE_TEXT)
val navigationController = getNavigationController()
viewModel.setChatId(id)
val messageAdapter = MessageAdapter(view.context) { uri ->
navigationController.openPhoto(uri)
}
val linearLayoutManager = LinearLayoutManager(view.context).apply {
stackFromEnd = true
}
binding.messages.run {
layoutManager = linearLayoutManager
adapter = messageAdapter
}
viewModel.contact.observe(viewLifecycleOwner) { contact ->
if (contact == null) {
Toast.makeText(view.context, "Contact not found", Toast.LENGTH_SHORT).show()
parentFragmentManager.popBackStack()
} else {
requireActivity().setLocusContext(LocusId(contact.shortcutId), null)
navigationController.updateAppBar { name, icon ->
name.text = contact.name
icon.setImageIcon(Icon.createWithAdaptiveBitmapContentUri(contact.iconUri))
startPostponedEnterTransition()
}
}
}
viewModel.messages.observe(viewLifecycleOwner) { messages ->
messageAdapter.submitList(messages)
linearLayoutManager.scrollToPosition(messages.size - 1)
}
if (prepopulateText != null) {
binding.input.setText(prepopulateText)
}
binding.input.setOnImageAddedListener { contentUri, mimeType, label ->
viewModel.setPhoto(contentUri, mimeType)
if (binding.input.text.isNullOrBlank()) {
binding.input.setText(label)
}
}
viewModel.photo.observe(viewLifecycleOwner) { uri ->
if (uri == null) {
binding.photo.visibility = View.GONE
} else {
binding.photo.visibility = View.VISIBLE
Glide.with(binding.photo).load(uri).into(binding.photo)
}
}
binding.voiceCall.setOnClickListener {
voiceCall()
}
binding.send.setOnClickListener {
send()
}
binding.input.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_SEND) {
send()
true
} else {
false
}
}
}