gpt4 book ai didi

android - 'setHasOptionsMenu(Boolean) : Unit' is deprecated. 在 Java 中已弃用

转载 作者:行者123 更新时间:2023-12-04 23:36:25 29 4
gpt4 key购买 nike

如何在 Android fragment 中声明菜单?我以前使用的方法现在已弃用。
原文:

    override fun onCreateView(...): View {
setHasOptionsMenu(true)
}
 override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
this.menu = menu
inflater.inflate(R.menu.menu, this.menu)
}

最佳答案

从开发人员文档中,这可以通过以下方式实现:

/**
* 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 when (menuItem.itemId) {
R.id.menu_clear -> {
// clearCompletedTasks()
true
}
R.id.menu_refresh -> {
// loadTasks(true)
true
}
else -> false
}
}
}, viewLifecycleOwner, Lifecycle.State.RESUMED)
}
Fragments setHasOptionsMenu deprecated, use setHasOptionsMenu

关于android - 'setHasOptionsMenu(Boolean) : Unit' is deprecated. 在 Java 中已弃用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71917856/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com