Ниже приведен код, который я использую:
Код: Выделить всё
class DashboardFragment : Fragment() {
private var \_binding: FragmentDashboardBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val dashboardViewModel =
ViewModelProvider(this).get(DashboardViewModel::class.java)
_binding = FragmentDashboardBinding.inflate(inflater, container, false)
val root: View = binding.root
binding.button.setOnClickListener {
Intent("com.nama.action").also { intent ->
intent.putExtra("nama", dashboardViewModel.text.value)
requireContext().sendBroadcast(intent)
}
}
val textView: TextView = binding.textDashboard
dashboardViewModel.text.observe(viewLifecycleOwner) {
textView.text = it
}
val br: BroadcastReceiver = MyBroadcastReceiver()
val filter = IntentFilter("com.nama.action")
ContextCompat.registerReceiver(requireContext().applicationContext, br, filter, ContextCompat.RECEIVER_NOT_EXPORTED)
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
Подробнее здесь: https://stackoverflow.com/questions/769 ... ot-working