Stackoverflower
Stackoverflower

Reputation: 322

How to replace a fragment with a fragment of another activity?

Suppose you have 2 activities, 1st activity is main activity with a bottom navigation bar which has 3 fragments as home, search, notification and 2nd activity is profile activity which contains the profile fragment. So now I have a button in main activity which intents me to profile activity so the bottom navigation is not here that I want.

But now in search fragment when I search a user and clicks on his profile, the search fragment should replace with the profile fragment. I did this

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

the above code from MainActivity is ok this is what i want but now in UserAdapter class,

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

Upvotes: 0

Views: 230

Answers (1)

Chuong Le Van
Chuong Le Van

Reputation: 284

Pls move your replace fragment logic from adapter to activity which contain replacement container(profile_fragment_container). Because in adapter can not find that replacement container.

You can handle through listener when click view in adapter.

Hope this help.

Upvotes: 1

Related Questions