【问题标题】:Did Actually needs to add fragments in mainfest是否实际上需要在清单中添加片段
【发布时间】:2020-06-12 13:07:55
【问题描述】:
override fun onOptionsItemSelected(item: MenuItem): Boolean {
    val id = item.itemId
    if (id ==R.id.refreshtabbutton){
        val intent : Intent = Intent(this,frag2::class.java)
        startActivity(intent)

    }
    return super.onOptionsItemSelected(item)
}

错误

   android.content.ActivityNotFoundException: Unable to find explicit activity class      {com.example.vlcclone/com.example.vlcclone.frag2}; have you declared this activity in your AndroidManifest.xml?
   at com.example.vlcclone.MainActivity.onOptionsItemSelected(MainActivity.kt:54)

如何解决这个问题?当用户单击菜单中的刷新按钮时,我想打开片段。

【问题讨论】:

  • “我想在用户点击菜单中的刷新按钮时打开片段”——您不要使用startActivity() 来显示片段。要么使用a FragmentTransaction with a FragmentManager,要么使用the Navigation component
  • @CommonsWare 不需要替换任何片段,但我必须打开已经存在的片段
  • 然后您创建一个新活动并使用片段事务将片段添加到该活动。然后你通过一个意图启动这个新活动。

标签: java android android-studio kotlin


【解决方案1】:

片段不是使用 Intents 打开的。您应该创建一个包含第二个 Fragment 的 Activity,或者您应该用第二个 Fragment 替换当前 Fragment(如果您有用于在当前 Activity 中保存该 Fragment 的容器)。 Intent 仅用于打开 Activity,而不是 Fragment (!)

https://developer.android.com/guide/components/fragments通过这个

【讨论】:

    猜你喜欢
    • 2012-03-12
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多