如何在片段中创建选项菜单

时间:2018-07-15 02:06:06

标签: android android-layout android-fragments kotlin

如何使用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)
}

我已经添加了,但是当我单击三个点或ifroom图标应用会崩溃。

创建选项菜单上的覆盖不适用于我的应用

1 个答案:

答案 0 :(得分:1)

为了拥有一个选项菜单,您需要在onCreate中告诉您有关它的片段,然后覆盖onCreateOptionsMenu。 然后要处理对项目的所有点击,请覆盖onOptionsItemSelected() 您的完整活动应如下所示:

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)
}

您还可以尝试使用android提供的actionBar小部件,以防appcompat一个不适合您