English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Android-Implementation Code for Switching Fragment Page Function

Scenario: Use Fragment to implement page switching.

Class structure:

First: Activity

In the Activity, use getSupportFragmentManager().beginTransaction() to fill a Fragment (the managing FragmentA)

Activity part code:

FragmentA fragment = FragmentA.newInstant(null);
getSupportFragmentManager().beginTransaction().add(R.id.f_tab_fragment,fragment).commit(); 

XML:

     <FrameLayout
        android:id="@"+id/fl_container"
        android:layout_width="match_parent"
        android:layout_above="@"+id/f_tab_fragment"
        android:layout_height="match_parent"/>
      <FrameLayout
        android:id="@"+id/f_tab_fragment"
        android:layout_width="match_parent"
        android:layout_height="52dp"
        android:layout_alignParentBottom="true"/> 

Second: FragmentA

Load a main FragmentA as the manager of other sub-leaves FragmentX.

Now, for example, there are two sub-leaves FragmentB and FragmentC.

FragmentA uses FragmentManager and FragmentTransaction to manage the switching of FragmentB and FragmentC 

FragmentA code:

 public class FragmentA extends BaseFragment {
  private static final String TAB_HOME = com.timediffproject.module.home.MyMainFragment.class.getName();
  private static final String TAB_TEST = com.timediffproject.module.home.TestFragment.class.getName();
  private BaseFragment mLastShowFragment;
  private static TabFragment fragment;
  public static TabFragment newInstant(Bundle bundle){
    if (fragment == null){
      fragment = new TabFragment();
      fragment.setArguments(bundle);
    }
    return fragment;
  }
  @Override
  public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    initTabInfo();
  }
  private void initTabInfo(){
    FragmentManager fm = getFragmentManager();
    if (fm == null){
      return;
    }
    FragmentTransaction ft = fm.beginTransaction();
    BaseFragment home = (BaseFragment) fm.findFragmentByTag(TAB_HOME);
    if (home != null){
      ft.hide(home);
    }
    BaseFragment test = (BaseFragment) fm.findFragmentByTag(TAB_TEST);
    if (test != null){
      ft.hide(test);
    }
    ft.commit();
  }
  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_tab, container, false);
  }
  @Override
  public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    view.findViewById(R.id.btn_change_home).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        switchTo(TAB_HOME, null);
      }
    });
    view.findViewById(R.id.btn_change_test).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        switchTo(TAB_TEST, null);
      }
    });
    switchTo(TAB_HOME, null);
  }
  //The method of switching Fragments (FragmentB, FragmentC)
  //tab is the class name of the Fragment (e.g., FragmentB.class.getName())
  //R.id.fl_container is in the layout of the Activity, not in the layout of FragmentA
  private void switchTo(String tab, Bundle bundle){
    //Initialize the class that manages Fragments
    FragmentManager fm = getFragmentManager();
    if (fm == null){
      return;
    }
    FragmentTransaction ft = fm.beginTransaction();
    //Find the Fragment with class name tab from the FragmentManager
    BaseFragment fragment = (BaseFragment) fm.findFragmentByTag(tab);
    if (fragment == null){
      fragment = (BaseFragment) Fragment.instantiate(getActivity(), tab);
      fragment.setArguments(bundle);
      ft.add(R.id.fl_container, fragment, tab);
    }else{
      ft.show(fragment);
    }
    //Hide the currently displayed Fragment
    if (mLastShowFragment != null) {
      ft.hide(mLastShowFragment);
    }
    //Record the last clicked Fragment
    mLastShowFragment = fragment;
    ft.commitAllowingStateLoss();
  }
} 

XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal" android:layout_width="match_parent"
  android:layout_height="52dp">
  <Button
    android:id="@"+id/btn_change_home"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Switch home"
    />
  <Button
    android:id="@"+id/btn_change_test"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Switch test"
    />
</LinearLayout> 

3: FragmentX (FragmentB, FragmentC)

The logic of the sub-page should be defined according to the specific business, and implemented in the same way as a general Fragment

 For example:

public class TestFragment extends BaseFragment {
  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {return inflater.inflate(R.layout.fragment_test, container, false);}
  }
  @Override
  public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
  }
} 

Now, it can be simply implemented-Implement page switching function by using bottom Tab to switch Fragment

Attachment:

 

PS: Errors encountered during implementation 

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

Correct way: The initialization layout of the related fragment should be added with false to establish a relationship with the parent layout.

Reason: Without it, the system will bind an unknown parent class to the view generated by this inflater. When you bind this fragment as a child page to an Activity or another fragment, the above error will occur.

@Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //The correct way is:
    //return inflater.inflate(R.layout.fragment_test, container, false);
    return inflater.inflate(R.layout.fragment_test, container);
   }   

 That's all for this article. I hope it will be helpful to everyone's learning and that everyone will support the Yelling Tutorial more.

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please send an email to codebox.com (replace # with @ when sending email) to report any violations, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.