Saturday, 21 June 2014

[KEY : FRAGMENT, ADDING FRAGMENT, ANDROID FRAGMENT, CREATING FRAGMENT]

FRAGMENT, ANDROID

Android activity is simple and best way to provide interface to user. Fragment are very similar to activity. But it will be much better if we call it small piece of activity. So an activity can have multiple fragments

Creating fragment in android

  1. Create simple class like "MyFirstFragment.java".
  2. Extend Fragment class into "MyFirstFragment.java".
  3. Fragement is almost ready. Now add required methods into it, Specifically you require two methods onCreateView() and onAttach() as mentioned below :

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub return super.onCreateView(inflater, container, savedInstanceState); }


    @Override public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); }

  4. Inflate your own xml file and return it as view. So finally onCreateView() will look like as below:

    @Override
     public View onCreateView(LayoutInflater inflater, 
       ViewGroup container, Bundle savedInstanceState) {
      
      View localView = inflater.inflate(R.layout.your_xml.xml, 
        container, false);
      
      return localView; //super.onCreateView(inflater, container, savedInstanceState);
     }
    

  5. Create global object of your parent activity

    YourActivity yourActivityObject;

  6. Initialize yourActivityObject in onAttach method so it will look as below:

     @Override
     public void onAttach(Activity activity) {
    
      yourActivityObject = (YourActivity)activity;
    
      super.onAttach(activity);
     }
    

Start / Call new fragment from fragment

 Fragment yourSecondFragment = new YourSecondFragment();

 FragmentManager fm = yourActivityObject.getSupportFragmentManager();

 //yourSecondFragment.setArguments(Bundle) // to pass argument to next fragment.

 fm.beginTransaction().replace(R.id.parent_activity_frame_layout, 
 yourSecondFragment).addToBackStack("myfragmentstring").commit();

 // addToBackStack method before commit is used to implement back button functionality later.  

Adding back button functionality to fragment

In parent activity add onBackPressed() method and paste the following code

int f = getSupportFragmentManager().getBackStackEntryCount();
  Log.v(tag, "onBackPressed ["+f+"]");
  if (f <= 1)
   this.finish();
  else {
   getSupportFragmentManager().popBackStackImmediate();
  }


No comments:

Post a Comment