Tuesday, 24 May 2016

Fragement in Android

01:47

Fragment:

Fragment represents a behavior or a portion of user interface in an Activity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities).
A fragment must always be embedded in an activity and the fragment's lifecycle is directly affected by the host activity's lifecycle. For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments. However, while an activity is running (it is in the resumed lifecycle state), you can manipulate each fragment independently, such as add or remove them. When you perform such a fragment transaction, you can also add it to a back stack that's managed by the activity—each back stack entry in the activity is a record of the fragment transaction that occurred. The back stack allows the user to reverse a fragment transaction (navigate backwards), by pressing the Back button.

Lifecycle :

Though a Fragment's lifecycle is tied to its owning activity, it has its own wrinkle on the standard activity lifecycle. It includes basic activity lifecycle methods such as onResume(), but also important are methods related to interactions with the activity and UI generation.
The core series of lifecycle methods that are called to bring a fragment up to resumed state (interacting with the user) are:
  1. onAttach(Activity) called once the fragment is associated with its activity.
  2. onCreate(Bundle) called to do initial creation of the fragment.
  3. onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment.
  4. onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity.onCreate().
  5. onViewStateRestored(Bundle) tells the fragment that all of the saved state of its view hierarchy has been restored.
  6. onStart() makes the fragment visible to the user (based on its containing activity being started).
  7. onResume() makes the fragment begin interacting with the user (based on its containing activity being resumed).
As a fragment is no longer being used, it goes through a reverse series of callbacks:
  1. onPause() fragment is no longer interacting with the user either because its activity is being paused or a fragment operation is modifying it in the activity.
  2. onStop() fragment is no longer visible to the user either because its activity is being stopped or a fragment operation is modifying it in the activity.
  3. onDestroyView() allows the fragment to clean up resources associated with its View.
  4. onDestroy() called to do final cleanup of the fragment's state.
  5. onDetach() called immediately prior to the fragment no longer being associated with its activity.

(1)First  of all create  FragementOne.java  file:

package testing.om.com.fragement77;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;



public class FragementOne extends Fragment {



   
public FragementOne() {
       
// Required empty public constructor
   
}



   
@Override
   
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       
// Inflate the layout for this fragment
       
return inflater.inflate(R.layout.fragement_layout_one, container, false);
    }


   

}


(2)write  code for  fragement_layout_one.xml file :

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:background="#800000" tools:context="testing.om.com.fragement77.FragementOne">



    <!-- TODO: Update blank fragment layout -->

    <TextView android:layout_width="match_parent" android:layout_height="match_parent"

        android:text="hello  one" />



</FrameLayout>
 
(3)write code for   FragementTwo.java  file:
 
package testing.om.com.fragement77;



import android.app.Fragment;

import android.os.Bundle;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;







public class FragementTwo extends Fragment {









    public FragementTwo()

    {

        // Required empty public constructor

    }







    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,

                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment

        return inflater.inflate(R.layout.fragment_layout_two, container, false);

    }







}
 


(4)write  code for  fragement_layout_two.xml file:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"

    android:background="#FFFF00"

    android:layout_height="match_parent" tools:context="testing.om.com.fragement77.FragementTwo">



    <!-- TODO: Update blank fragment layout -->

    <TextView android:layout_width="match_parent" android:layout_height="match_parent"

        android:text="@string/hello_blank_fragment" />



</FrameLayout>



(5)now  write code for activity   file which attach this  two fragements:
Write code for   MainActivity.java
package testing.om.com.fragement77;



import android.app.FragmentManager;

import android.app.FragmentTransaction;

import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.Button;



public class MainActivity extends AppCompatActivity {

   Button b1,b2;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        b1=(Button)findViewById(R.id.b1);

        b2=(Button)findViewById(R.id.b2);



        b1.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                FragmentManager fm=getFragmentManager() ;

                FragmentTransaction ft=fm.beginTransaction();

                FragementOne  f1=new FragementOne();

                ft.add(R.id.r1,f1);

                ft.commit();





            }

        });



        b2.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view1) {

                FragmentManager fm=getFragmentManager() ;

                FragmentTransaction ft=fm.beginTransaction();

                FragementTwo  f2=new FragementTwo();

                ft.add(R.id.r1,f2);

                ft.commit();

            }

        });

    }



    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.menu_main, menu);

        return true;

    }



    @Override

    public boolean onOptionsItemSelected(MenuItem item) {

        // Handle action bar item clicks here. The action bar will

        // automatically handle clicks on the Home/Up button, so long

        // as you specify a parent activity in AndroidManifest.xml.

        int id = item.getItemId();



        //noinspection SimplifiableIfStatement

        if (id == R.id.action_settings) {

            return true;

        }



        return super.onOptionsItemSelected(item);

    }

}

(6)write  code for activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.CoordinatorLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"

    android:layout_height="match_parent" android:fitsSystemWindows="true"

    tools:context=".MainActivity">



    <android.support.design.widget.AppBarLayout android:layout_height="wrap_content"

        android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay">



        <android.support.v7.widget.Toolbar android:id="@+id/toolbar"

            android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"

            android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" />



    </android.support.design.widget.AppBarLayout>



    <include layout="@layout/content_main" />



    <android.support.design.widget.FloatingActionButton android:id="@+id/fab"

        android:layout_width="wrap_content" android:layout_height="wrap_content"

        android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin"

        android:src="@android:drawable/ic_dialog_email" />



</android.support.design.widget.CoordinatorLayout>

(7)write code for  content_main.xml file:
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"

    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    android:paddingBottom="@dimen/activity_vertical_margin"

    app:layout_behavior="@string/appbar_scrolling_view_behavior"

    tools:showIn="@layout/activity_main" tools:context=".MainActivity">





    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="start fragement one"

        android:id="@+id/b1"

        android:layout_alignParentTop="true"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="38dp" />



    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="start fragement two"

        android:id="@+id/b2"

        android:layout_below="@+id/b1"

        android:layout_alignLeft="@+id/b1"

        android:layout_alignStart="@+id/b1"

        android:layout_marginTop="37dp" />



    <RelativeLayout

        android:id="@+id/r1"

        android:layout_width="match_parent"

        android:layout_height="150dp"

        android:layout_below="@+id/b2">



    </RelativeLayout>



</RelativeLayout>


Output :



================================================================================================================================================
Fragment   example   using   xml   :
 
 
 (1)write code for  ArticleFragment.java file 
 
package testing.om.com.fragementusingxml;



import android.app.Fragment;

import android.os.Bundle;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;







public class ArticleFragment extends Fragment {





    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,

                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment

        return inflater.inflate(R.layout.fragment_article, container, false);

    }





}

   (2)write code for  fragment_article.xml  file :
 
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context="testing.om.com.fragementusingxml.ArticleFragment">

    <TextView android:layout_width="match_parent" android:layout_height="match_parent"

        android:text="om is back" />



</FrameLayout>

(3)write code for  ReaderFragment.java file:

package testing.om.com.fragementusingxml;



import android.app.Fragment;

import android.os.Bundle;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;







public class ReaderFragment extends Fragment {





    public ReaderFragment() {

        // Required empty public constructor

    }







    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,

                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment

        return inflater.inflate(R.layout.fragment_reader, container, false);



    }







}
 
  (4) write   code for fragment_reader.xml file :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context="testing.om.com.fragementusingxml.ReaderFragment">



    <!-- TODO: Update blank fragment layout -->

    <TextView android:layout_width="match_parent" android:layout_height="match_parent"

        android:text="@string/hello_blank_fragment" />



</FrameLayout>
 
 
 
(5)write code for  MainActivity.java file:
 
package testing.om.com.fragementusingxml;



import android.os.Bundle;

import android.support.v4.app.FragmentActivity;



public class MainActivity extends FragmentActivity {



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);





    }





}
 
 
 
 
(6)activity_main.xml file :
 
<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.CoordinatorLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"

    android:layout_height="match_parent" android:fitsSystemWindows="true"

    tools:context=".MainActivity">



    <android.support.design.widget.AppBarLayout android:layout_height="wrap_content"

        android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay">



        <android.support.v7.widget.Toolbar android:id="@+id/toolbar"

            android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"

            android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" />



    </android.support.design.widget.AppBarLayout>



    <include layout="@layout/content_main" />



    <android.support.design.widget.FloatingActionButton android:id="@+id/fab"

        android:layout_width="wrap_content" android:layout_height="wrap_content"

        android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin"

        android:src="@android:drawable/ic_dialog_email" />



</android.support.design.widget.CoordinatorLayout>
 
(7)write code for  content_main.xml file:
 
<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"

    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    android:paddingBottom="@dimen/activity_vertical_margin"

    app:layout_behavior="@string/appbar_scrolling_view_behavior"

    tools:showIn="@layout/activity_main" tools:context=".MainActivity">



    <fragment android:name="testing.om.com.fragementusingxml.ArticleFragment"

        android:id="@+id/article_fragment"

        android:layout_weight="1"

        android:layout_width="100dp"

        android:gravity="left"

        android:layout_height="match_parent"

        android:layout_alignParentTop="true"

        android:layout_alignParentLeft="true"

        android:layout_alignParentStart="true" />



    <fragment android:name="testing.om.com.fragementusingxml.ReaderFragment"

        android:id="@+id/reader_fragment1"

        android:layout_weight="2"

        android:layout_width="100dp"

        android:layout_height="match_parent"

        android:layout_alignParentTop="true"

        android:layout_alignParentRight="true"

        android:layout_alignParentEnd="true" />







</RelativeLayout>
 
 
Output:







Written by

We are Creative Blogger Theme Wavers which provides user friendly, effective and easy to use themes. Each support has free and providing HD support screen casting.

0 comments:

Post a Comment

 

© 2013 ANDROID TRAINING IN MUMBAI BY OM SIR. All rights resevered. Designed by Templateism

Back To Top