1、效果图
2、未添加menu前的界面
3、在menu文件夹添加menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"><itemandroid:id="@+id/action_add_dish"android:icon="@drawable/ic_add_foreground"android:title="@string/add_dish"app:showAsAction="always"/></menu>
4、在所要显示的界面中复写onCreate方法,添加代码
setHasOptionsMenu(true)
override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setHasOptionsMenu(true)}
5、加载menu布局
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {inflater.inflate(R.menu.menu_all_dishes,menu)super.onCreateOptionsMenu(menu, inflater)}
6、添加点击事件
override fun onOptionsItemSelected(item: MenuItem): Boolean {when(item.itemId){R.id.action_add_dish -> {val tost:Toast = Toast.makeText(requireActivity(),"menu is clicked",Toast.LENGTH_SHORT)tost.setGravity(Gravity.CENTER,100,0)tost.show()}}return super.onOptionsItemSelected(item)}
注:
fragment代码
package com.dummy.fvedish.ui.homeimport android.os.Bundle
import android.view.*
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.dummy.fvedish.R
import com.dummy.fvedish.databinding.FragmentHomeBindingclass HomeFragment : Fragment() {private var _binding: FragmentHomeBinding? = null// This property is only valid between onCreateView and// onDestroyView.private val binding get() = _binding!!override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setHasOptionsMenu(true)}override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View {val homeViewModel =ViewModelProvider(this).get(HomeViewModel::class.java)_binding = FragmentHomeBinding.inflate(inflater, container, false)val root: View = binding.rootval textView: TextView = binding.textHomehomeViewModel.text.observe(viewLifecycleOwner) {textView.text = it}return root}override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {inflater.inflate(R.menu.menu_all_dishes,menu)super.onCreateOptionsMenu(menu, inflater)}override fun onOptionsItemSelected(item: MenuItem): Boolean {when(item.itemId){R.id.action_add_dish -> {val tost:Toast = Toast.makeText(requireActivity(),"menu is clicked",Toast.LENGTH_SHORT)tost.setGravity(Gravity.CENTER,100,0)tost.show()}}return super.onOptionsItemSelected(item)}override fun onDestroyView() {super.onDestroyView()_binding = null}
}