这是个初学者的问题。自从在片段中使用“setHasOptionsMenu(真)”的旧范例最近在Android中被废弃以来,我一直试图将我的应用程序转换成文档中概述的最新方案。关于这方面的所有解释,我可以从上述文档中找到围绕以下代码片段的中心:
代码语言:javascript复制/**
* Using the addMenuProvider() API directly in your Activity
**/
class ExampleActivity : ComponentActivity(R.layout.activity_example) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Add menu items without overriding methods in the Activity
addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
// Add menu items here
menuInflater.inflate(R.menu.example_menu, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
// Handle the menu selection
return true
}
})
}
}
/**
* Using the addMenuProvider() API in a Fragment
**/
class ExampleFragment : Fragment(R.layout.fragment_example) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// The usage of an interface lets you inject your own implementation
val menuHost: MenuHost = requireActivity()
// Add menu items without using the Fragment Menu APIs
// Note how we can tie the MenuProvider to the viewLifecycleOwner
// and an optional Lifecycle.State (here, RESUMED) to indicate when
// the menu should be visible
menuHost.addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
// Add menu items here
menuInflater.inflate(R.menu.example_menu, menu)
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
// Handle the menu selection
return true
}
}, viewLifecycleOwner, Lifecycle.State.RESUMED)
}现在,我已经尝试将此代码添加到我的主要活动(扩展AppCompatActivity() )和相关片段中。无论哪里写着"R.menu.example_menu“,我都插入了我自己的菜单布局文件,这些文件基本上只包含一个设置项,大部分时间都是这样。
但是,虽然代码编译时没有错误,但实际上没有项添加到菜单栏中。我遗漏了什么?我是否应该手动添加项目,上面写着“这里添加菜单项”?然而,编写诸如“menu.add(”设置“)之类的东西似乎也没有效果。