Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/203.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何用另一个活动的片段替换片段?_Android_Android Fragments_Android Activity - Fatal编程技术网

Android 如何用另一个活动的片段替换片段?

Android 如何用另一个活动的片段替换片段?,android,android-fragments,android-activity,Android,Android Fragments,Android Activity,假设您有2个活动,第一个活动是主活动,底部有一个导航栏,其中有3个片段作为主页、搜索、通知,第二个活动是包含概要文件片段的概要文件活动。所以现在我在主活动中有一个按钮,它打算让我分析活动,所以底部导航不是我想要的 但现在在搜索片段中,当我搜索一个用户并单击他的个人资料时,搜索片段应该替换为个人资料片段。我做了 profileButton.setOnClickListener { startActivity(Intent(this@MainActivity, Profile

假设您有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()
            }

请将您的替换片段逻辑从适配器移动到包含替换容器(profile\u fragment\u container)的活动。因为在适配器中找不到替换容器

在适配器中单击“查看”时,可以通过侦听器进行处理


希望有帮助。

为什么你要将侦听器从适配器传递到活动,然后你才能处理该事件中的逻辑?@Chunglevan适配器是搜索片段中recycleView中的用户项目视图,因此当用户单击该项目时,它将转到profile片段,其他操作将在那里发生。我正在关注youtube上的一个教程,但我的设计与他不同,所以我面临着这个问题。你的逻辑代码替换片段时,是否在logcat中没有错误消息就无法工作?@Chunglevan替换片段的逻辑无法工作应用程序崩溃,logcat说“找不到id profile\u fragment\u container and ProfileFragment()的容器”,但intent的abouve注释代码正在工作,但我需要片段事务。我发布了我的答案。请尝试此操作否。您只需将
holder.userItemView.setOnClickListener中的逻辑代码从适配器替换为活动(或片段)包含该适配器。我将代码放置在搜索片段中,它给出了关于持有者和McContext的错误,当我将其放置到mainActivity时,它也会这样做。searchFragment或mainActivity是否包含查看配置文件\u fragment\u容器?好的,我再次解释,当用户搜索用户并单击MainA的searchFragment中的userItemView时,我需要activity然后用户横切到ProfileFragment,它位于另一个名为ProfileActivity的活动中,profile\u fragment\u容器的id为fragment\u profile.xml.bro。请记住,当您将片段替换到容器(profile\u fragment\u容器)中时,您必须执行该活动(或片段)中的逻辑,使布局包含该容器(profile\u fragment\u container)。否则将出现错误,无法找到id profile\u fragment\u container的容器