【问题标题】:setSupportActionBar inside of a Fragment片段内的 setSupportActionBar
【发布时间】:2018-10-30 08:11:30
【问题描述】:

我有一个片段:

class HomeFragment : Fragment() { ... }

现在我正在尝试向其添加操作栏,但这不起作用:

setSupportActionBar(findViewById(R.id.toolbar_main))

如何设置 Support,然后将 Items 添加到 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)
    }
}

提前致谢!

【问题讨论】:

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


    【解决方案1】:

    在你的Fragment 中覆盖onCreateOptionsMenu 并在你的menu 内部膨胀。比在FragmentonCreate 方法中将setHasOptionsMenu() 设置为true。首先根据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)
    }
    

    【讨论】:

    • 但是如果我尝试在 Fragment 中充气,它会说 menuInflater 有一个未解析的引用。你能举个例子告诉我怎么做吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    • 2019-03-07
    • 2021-05-23
    • 2017-05-15
    相关资源
    最近更新 更多