Sunday, 10 February 2019

5/2/2019 - Static fragment and dynamic fragment



Static fragment

  • Static fragment is a fragment that can't be change during runtime.
  • It uses <fragment> widget from Android Studio.
  • Only .xml file.
  • Nothing need to be declared in MainActivity.java



Dynamic fragment

  • Dynamic fragment is a fragment that can be change during runtime.
  • It uses FrameLayout widget to be a container for it.
  • It needed to be declare in the MainActivity.java

For example,

Dynamic fragment sample code:

//MainActivity.java
public class MainActivity extends AppCompatActivity
{
   //set as public static, so it can be use in other fragment activity too
   public static FragmentManager frag_manager;

   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      frag_manager = getSupportFragmentManager;
      
      //the FrameLayout id = fragContainer in activity_main.xml
      if (findViewById(R.id.fragContainer) != null)
      {
         //if the item is saved, which means that there is already a item there
         if (savedInstanceState != null)
         {
            return;
         }
         
         //begin the transaction for fragment
         FragmentTransaction frag_trans = frag_manager.beginTransaction();

         //declare the first fragment item, which is the FirstFrag.java
         FirstFrag first_frag = new FirstFrag();

         //add the first_frag.xml to the FrameLayout container
         frag_trans.add(R.id.fragContainer,first_frag,false);

         //commit the fragment
         frag_trans.commit();
      }
   }

}


The code above will add the fragment into a FrameLayout container. The fragment inside the container can be change, eg. currently is first_frag.xml in FirstFrag.java, but it can be chage to second.frag.xml in SecondFrag.java too, a button can be add to perform the change of fragement during runtime.







No comments:

Post a Comment

18/7/2019 - Survive that planning

Planning A top-down shooting game Player use WASD to move Use mouse cursor to aim Mouse left-click to shoot, and right click to throw ...