我有一个片段:
class HomeFragment : Fragment() { ... }
现在我尝试添加一个Actionbar,但这不起作用:
setSupportActionBar(findViewById(R.id.toolbar_main))
如何设置支持,然后将项目添加到ActionBar?
这是它在AppCompatActivity中的工作原理:
// This adds items to the ActionBar
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_toolbar_main, menu)
return true
}
// This is the OnClickListener for the Buttons in the ActionBar
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.toolbar_edit -> {
true
}
R.id.toolbar_search -> {
true
}
else -> {
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
super.onOptionsItemSelected(item)
}
}
提前非常感谢!
答案 0 :(得分:1)
覆盖onCreateOptionsMenu
中的Fragment
,并在menu
内充气。比onCreate
方法Fragment
设置setHasOptionsMenu()
为真。首先根据Fragment
创建clear
菜单来扩充不同的菜单。
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
super.onCreateOptionsMenu(menu, inflater)
inflater?.inflate(Your menu here, menu)
}