0

How can via Kotlin mapOf map buttons key to value? I have such code.

reference to start_button is correct, by clickin on it I can open corect button in xml, but in debug mode buttonsMap value (start_button) is null.

class StartDialog : DialogFragment(){
private val buttonsMap: Map<String, Button> by lazy(LazyThreadSafetyMode.NONE) {
        mapOf(
            "startButton" to start_button
        )
    }

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = Dialog(requireContext())

        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog.setContentView(R.layout.start_dialog)
        
        displayButtons(Wrapper(requireContext())
        return dialog
}

private fun displayButtons(wrapper: Wrapper) {
        wrapper.queryButtons(object : Wrapper.OnQueryButtonListener {
            override fun onSuccess(buttons: List<ButtonDetails>) {
                buttons.forEach { button ->
                    buttonsMap[button.key]?.apply {
                        text = "${button.description}"
                        setOnClickListener {
                            wrapper.startProcess(requireActivity(), button)
                        }
                    }
                }
            }
        })
    }
}

<androidx.appcompat.widget.AppCompatButton
android:id="@+id/start_button"
android:layout_width="300dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:layout_marginTop="15dp" 
android:gravity="center"
android:textColor="@color/ef_white"
android:text="Start"
android:textSize="16sp">
Slava
  • 443
  • 4
  • 12
  • 1
    please provide more context: what are you trying to achieve? When and what for is that map used? From just looking at the snipped one can assume that you use kotlinx.synthetic properties and also cache a view reference - both of those things are a very bad idea and may / will cause you a lot of headaches, so maybe you'd want to explain your goals so we can point you in the right direction. – Droidman Sep 29 '22 at 08:14
  • provided more code. buttonsMap[button.key] get back the correct button.key, but buttonsMap has only key ("startButton") with null value, but must be correct button object – Slava Sep 29 '22 at 08:26
  • 1
    most likely it is null because `displayButtons` is called before `onCreateDialog` (and probably `onCreateView`) returns, have you tried moving this line `displayButtons(Wrapper(requireContext())` to `onActivityCreated`? – Droidman Sep 30 '22 at 10:32
  • Yes, thanks, I got it, I have changed to onCreateView and onViewCreated without onCreateDialog – Slava Sep 30 '22 at 11:00

0 Answers0