【问题标题】:How to replace a fragment with a fragment of another activity?如何用另一个活动的片段替换片段?
【发布时间】:2020-04-14 11:20:29
【问题描述】:

假设您有 2 个活动,第一个活动是主要活动,底部导航栏有 3 个片段作为主页、搜索、通知,第二个活动是包含个人资料片段的个人资料活动。所以现在我在主要活动中有一个按钮,它打算让我分析活动,所以底部导航不是我想要的。

但是现在在搜索片段中,当我搜索用户并点击他的个人资料时,搜索片段应该替换为个人资料片段。我这样做了

 profileButton.setOnClickListener {
           startActivity(Intent(this@MainActivity, ProfileActivity::class.java ))
        }

上面来自 MainActivity 的代码没问题,这是我想要的,但现在在 UserAdapter 类中,

holder.userItemView.setOnClickListener {
                //...some code for sharedPreference

             //the below code works for intent but i won't it
            // mContext.startActivity(Intent(mContext, ProfileActivity::class.java )) 

           //I want this but this is not working
              (mContext as FragmentActivity).supportFragmentManager.beginTransaction()
                        .replace(R.id.profile_fragment_container, ProfileFragment()).commit()
            }

【问题讨论】:

  • 为什么你将监听器从适配器传递给活动,然后你可以处理该事件中的逻辑?
  • @ChuongLeVan 该适配器是搜索片段中 recycleView 中的用户项目视图,因此当用户单击该项目时,它会转到配置文件片段,其他操作将在那里发生。我正在关注 youtube 上关于此的教程,但我的设计与他不同,所以我面临这个问题。
  • 在 logcat 中没有错误消息的情况下,您替换片段的逻辑代码是否不起作用?
  • @ChuongLeVan 替换片段的逻辑不起作用应用程序崩溃并且 logcat 说“找不到 id profile_fragment_container 和 ProfileFragment() 的容器”但是上面的意图注释代码正在工作,但我想要片段交易。
  • 我发布了我的答案。请试试这个

标签: android android-fragments android-activity


【解决方案1】:

请将您的替换片段逻辑从适配器移动到包含替换容器(profile_fragment_container)的活动。因为在适配器中找不到那个替换容器。

您可以在适配器中单击视图时通过侦听器进行处理。

希望对您有所帮助。

【讨论】:

  • 没有。您只需将holder.userItemView.setOnClickListener 中的逻辑代码从适配器替换为包含该适配器的活动(或片段)。
  • 我放置了代码来搜索片段,它给了我关于持有者和 mContext 的错误,当我将它放置到 mainActivity 时它也会这样做。
  • searchFragment 或 mainActivity 是否包含视图 profile_fragment_container?
  • 好的,我再次解释说,当用户搜索用户并单击 MainActivity 的 SearchFragment 中的 userItemView 然后用户横切到另一个名为 ProfileActivity 的活动中的 ProfileFragment 并且 profile_fragment_container 是片段配置文件.xml .
  • 兄弟。请记住,当您将片段替换为容器(profile_fragment_container)时。你必须在该活动(或片段)中执行逻辑,布局包含该容器(profile_fragment_container)。否则会出错找不到 id profile_fragment_container 的容器
猜你喜欢
  • 2023-04-11
  • 1970-01-01
  • 1970-01-01
  • 2011-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多