0

I'm trying to create context menu inside fragment. My sequence of actions:

1)Create resource directory and menu file (context_menu.xml)

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/download"
    android:title="Download"/>

<item android:id="@+id/hello"
    android:title="Hello"/>

<item android:id="@+id/bye"
    android:title="Bye"/>

2)Setup button inside oncreateView()

val button = view.findViewById<Button>(R.id.download_button)
    registerForContextMenu(button)
    button.setOnClickListener {
        Toast.makeText(requireContext(), "Click", Toast.LENGTH_SHORT).show()
    }

Button works. Toast appears.

3)Override method onCkeateContextMenu() inside my fragment

override fun onCreateContextMenu(
    menu: ContextMenu,
    v: View,
    menuInfo: ContextMenu.ContextMenuInfo?
) {
    super.onCreateContextMenu(menu, v, menuInfo)
    requireActivity().menuInflater.inflate(R.menu.context_menu, menu)
}

Pressing the button does not open the menu. What could be the problem?

Novikov
  • 11
  • 2
  • Does this answer your question? [Inappropriate Context Menu within a Fragment](https://stackoverflow.com/questions/20825118/inappropriate-context-menu-within-a-fragment) – jeprubio Feb 19 '21 at 16:59

1 Answers1

0

After registering the context menu with registerForContextMenu(), you need to start the action mode with activity.startSupportActionMode(someCallback)

Zain
  • 37,492
  • 7
  • 60
  • 84
  • I register the context menu inside fragment onCreateView() method and there i can't call startSupportActionMode(someCallback) becauseactivity from requireActivity() method doesn't contain such method. – Novikov Feb 19 '21 at 17:11
  • @Novikov you need to cast `requireActivity()` to your Activity that hosts this fragment .. like `(requireActivity() as MainActivity).startSupportActionMode(callback)` .. change `MainActivity` to your activity name – Zain Feb 19 '21 at 17:14
  • i did what you told me, but it doesn't helps! – Novikov Feb 19 '21 at 17:32