4

how to add option menu in fragment using kotlin

class HomeFragment : Fragment() {

companion object {
    lateinit var drawerLayout:DrawerLayout
    lateinit var toolbar: android.support.v7.widget.Toolbar
    private lateinit var toggle: ActionBarDrawerToggle



}



override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {
    // Inflate the layout for this fragment
    val v = inflater.inflate(R.layout.fragment_home, container, false)
    setHasOptionsMenu(true)

    toolbar = v.findViewById(R.id.toolBar) as Toolbar
    toolbar.inflateMenu(R.menu.menuhome)




    drawerLayout = v.findViewById(R.id.drawer_Layout)

    // Creating toggle

    toggle = ActionBarDrawerToggle(activity, drawerLayout, toolbar,R.string.navigaionopen,R.string.drawerClosed)
    drawerLayout.addDrawerListener(toggle)
    toggle.syncState()






    return v
}


override fun onOptionsItemSelected(item: MenuItem?): Boolean {
    when(item!!.itemId){
        R.id.search -> {Toast.makeText(context,"Search",Toast.LENGTH_SHORT).show()}

        R.id.send -> {Toast.makeText(context,"Send selected",Toast.LENGTH_SHORT).show()}
    }
    return super.onOptionsItemSelected(item)
}

I have added but when i click on three dot or ifroom icon app going to crashed.

overide on create option menu is not working on my app

1
  • 1
    What errors are you getting?Post it And How overide on create option menu not working?What do you mean? Commented Jul 15, 2018 at 2:25

1 Answer 1

17

in order to have an options menu you need to tell your fragment about it in onCreate after which you override onCreateOptionsMenu. then to handle any clicks on the items override onOptionsItemSelected() your full Activity should look like this:

class TestFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setHasOptionsMenu(true)
}

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
    inflater.inflate(R.menu.menu_test, menu);

    super.onCreateOptionsMenu(menu, inflater)
}

You can also try to use the actionBar widget provided by android incase the appcompat one doesn't work for you

Sign up to request clarification or add additional context in comments.

1 Comment

The above option is deprecated. new way is defined here. stackoverflow.com/a/73080607/4036739

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.