简体   繁体   中英

How to change fragment from another fragment an apply it on the main_content layout?

I'm struggling with the changing of a fragment from another fragment. In my main_activity i have a layout-file with a bottomnavigationview and a framelayout for the content on the page. The changing from fragment to fragment on the navigationview workes fine, but if i access a new "subfragment" from a fragment, the new fragment is transparent.

Any suggestions? code below from my fragment and my mainactivity.

MainActivity parentActivity = (MainActivity) getActivity();
            parentActivity.switchContent(new VisArrangementInfo(), data, true);

switchContent inside MainActivity:

public void switchContent(final Fragment fragment, Bundle data, final Boolean addToBackStackOption){
getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.content_frame, fragment)
                .addToBackStack(null)
                .commit();

}

The id content_frame is the id for the layoutfile for my MainActivity. the bottomnavigationview and the framelayout is in this file. the ID for the framelayout is "main_frame".

After my understanding i would want to change the "main_frame" and not the "content_fram" since it's here the main-content is supposed to be. When i do that i can't find the layout for the fragment i try to open at all. Is it because i'm trying to replace the framelayout instead of the whole layout?

In your Fragment A define an interface.

public interface FragmentEventListener {
    void onFragmentChangeEvent(Fragment newFragment);
}

private FragmentEventListener listener;
public void setEventListener(FragmentEventListener listener) {
    this.listener = listener;
}

In your fragment, when you want to change the fragment, call the method.

if (listener != null) {
    listener.onFragmentChangeEvent(FragmentB);
}

In your main activity, implement FragmentEventListener , so you can switch to Fragment B from MainActivity.

public class MainActivity  implements FragmentA.FragmentEventListener {
...
...
fragmentB.setEventListener(this); // here identify the listener.
....

@Override
public void onFragmentChangeEvent(Fragment newFragment) {
    switchContent  // Switch to Fragment B here
}

In the first time use add instead of replace :

public void switchContent(final Fragment fragment, Bundle data, final Boolean addToBackStackOption){
getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.content_frame, fragment)
                .addToBackStack(null)
                .commit();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM