Aditya panther
Aditya panther

Reputation: 53

How to create option menu in fragment

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

Upvotes: 4

Views: 9768

Answers (1)

Austine Gwa
Austine Gwa

Reputation: 812

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

Upvotes: 17

Related Questions