片段内的setSupportActionBar

时间:2018-05-20 14:26:47

标签: android android-fragments kotlin android-actionbar android-toolbar

我有一个片段:

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

提前非常感谢!

1 个答案:

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