Wednesday 17 August 2016

Fragment



A 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).
Some Point -
1.       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.
2.       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.
3.       When you add a fragment as a part of your activity layout, it lives in a ViewGroup inside the activity's view hierarchy and the fragment defines its own view layout.
4.       You can insert a fragment into your activity layout by declaring the fragment in the activity's layout file, as a <fragment> element, or from your application code by adding it to an existing ViewGroup.

Design Philosophy
Android introduced fragments in Android 3.0 (API level 11), primarily to support more dynamic and flexible UI designs on large screens, such as tablets. Because a tablet's screen is much larger than that of a handset, there's more room to combine and interchange UI components.
1.       By dividing the layout of an activity into fragments, you become able to modify the activity's appearance at runtime and preserve those changes in a back stack that's managed by the activity.
2.        you can include one fragment in multiple activities, so you should design for reuse and avoid directly manipulating one fragment from another fragment.



https://developer.android.com/images/fundamentals/fragments.png

Code -
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:paddingBottom="@dimen/activity_vertical_margin"
   
android:paddingLeft="@dimen/activity_horizontal_margin"
   
android:paddingRight="@dimen/activity_horizontal_margin"
   
android:paddingTop="@dimen/activity_vertical_margin"
   
android:background="#06AEC9"
   
android:orientation="vertical"
   
tools:context="sichlearning.example.com.testone.MainActivity">

    <
TextView
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:text="Fragment Example"
       
android:id="@+id/txt1"
       
android:textAppearance="?android:textAppearanceLarge"
       
android:gravity="center"
       
android:textColor="#ffffff"
       
/>

    <
RelativeLayout
       
android:layout_width="match_parent"
       
android:layout_height="370dp"
       
android:id="@+id/fragment_container"
       
android:layout_marginTop="30dp"
       
>

    </
RelativeLayout>

</
LinearLayout>
MainActivity.java
public class MainActivity extends Activity

{



    @Override

    public void onCreate(Bundle savedInstanceState)

    {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        FragmentManager fragmentManager=getFragmentManager();

        FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();

        LoginFragment loginFragment=new LoginFragment();

        fragmentTransaction.add(R.id.fragment_container,loginFragment);

        fragmentTransaction.commit();

    }

    public void gotonewusr(View view)

    {

        FragmentManager fragmentManager=getFragmentManager();

        FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();

        RegisterFragment registerFragment=new RegisterFragment();

        fragmentTransaction.add(R.id.fragment_container, registerFragment);

        fragmentTransaction.commit();

    }

    public void returnlogin(View view)

    {

        FragmentManager fragmentManager=getFragmentManager();

        FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();

        LoginFragment loginFragment=new LoginFragment();

        fragmentTransaction.replace(R.id.fragment_container, loginFragment);

        fragmentTransaction.commit();

    }



}
activity_register_fragment.xml
<?xml version="1.0" encoding="utf-8"?>

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

    android:orientation="vertical" android:layout_width="match_parent"

    android:layout_height="370dp"

    android:background="#ffffff"

    android:padding="16dp"

    >

    <TextView

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="SIGNUP HERE"

        android:textAppearance="?android:textAppearanceLarge"

        android:gravity="center"

        android:textColor="#222222"

        android:layout_marginTop="10dp"

        />

    <EditText

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="Username"

        android:textSize="20dp"

        android:textColor="#ff69b4"

        android:background="#dedede"

        android:id="@+id/rusrname"

        android:layout_centerHorizontal="true"

        android:padding="10dp"

        android:layout_marginTop="30dp"

        />

    <EditText

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="Password"

        android:textSize="20dp"

        android:textColor="#ff69b4"

        android:textColorHint="#ffffff"

        android:background="#dedede"

        android:id="@+id/rpassword"

        android:layout_centerHorizontal="true"

        android:padding="10dp"

        android:layout_marginTop="10dp"

        />

    <EditText

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="Confirm Password"

        android:textSize="20dp"

        android:textColor="#ff69b4"

        android:textColorHint="#ffffff"

        android:background="#dedede"

        android:id="@+id/rcpassword"

        android:layout_centerHorizontal="true"

        android:padding="10dp"

        android:layout_marginTop="10dp"

        />

    <Button

        android:layout_width="200dp"

        android:layout_height="wrap_content"

        android:text="Submit"

        android:textAppearance="?android:textAppearanceLarge"

        android:layout_gravity="center"

        android:padding="15dp"

        android:layout_marginTop="15dp"

        />

    <Button

        android:layout_width="200dp"

        android:layout_height="wrap_content"

        android:text="Login"

        android:id="@+id/brtnlogin"

        android:textColor="#ff8800"

        android:background="#ffffff"

        android:layout_gravity="center"

        android:layout_marginTop="15dp"

        android:onClick="returnlogin"

        />

</LinearLayout>


RegisterFragment.java
import android.os.Bundle;

import android.support.annotation.Nullable;



import android.app.Fragment;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;



public class RegisterFragment extends Fragment {



    @Nullable

    @Override

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

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

    }

}
activity_login_fragment.xml
<?xml version="1.0" encoding="utf-8"?>

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

    android:orientation="vertical" android:layout_width="match_parent"

    android:layout_height="370dp"

    android:background="#ffffff"

    android:padding="16dp"

    >

    <TextView

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="LOGIN"

        android:textAppearance="?android:textAppearanceLarge"

        android:gravity="center"

        android:textColor="#222222"

        android:layout_marginTop="20dp"

        />

    <EditText

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="Username"

        android:textSize="25dp"

        android:textColor="#ff69b4"

        android:background="#dedede"

        android:id="@+id/lusrname"

        android:layout_centerHorizontal="true"

        android:padding="10dp"

        android:layout_marginTop="40dp"

        />

    <EditText

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:hint="Password"

        android:textSize="25dp"

        android:textColor="#ff69b4"

        android:textColorHint="#ffffff"

        android:background="#dedede"

        android:id="@+id/lpassword"

        android:layout_centerHorizontal="true"

        android:padding="10dp"

        android:layout_marginTop="10dp"

        />

    <Button

        android:layout_width="200dp"

        android:layout_height="wrap_content"

        android:text="Submit"

        android:textAppearance="?android:textAppearanceLarge"

        android:layout_gravity="center"

        android:padding="20dp"

        android:layout_marginTop="15dp"

        />

    <Button

        android:layout_width="200dp"

        android:layout_height="wrap_content"

        android:text="new user?"

        android:textColor="#ff8800"

        android:background="#ffffff"

        android:layout_gravity="center"

        android:layout_marginTop="15dp"

        android:onClick="gotonewusr"

        />

</LinearLayout>
 
LoginFragment.java
import android.app.Fragment;

import android.os.Bundle;

import android.support.annotation.Nullable;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;



public class LoginFragment extends Fragment {



    @Nullable

    @Override

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

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

    }

}
-------------------------------------------------------------------------------------------
Explaination -1
FragmentManager fragmentManager=getFragmentManager();
        FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
        LoginFragment loginFragment=new LoginFragment();
        fragmentTransaction.add(R.id.fragment_container,loginFragment);
        fragmentTransaction.commit();
You can also use below code, instead of  above code
if (savedInstanceState == null) {

    getFragmentManager()

            .beginTransaction()

            .add(R.id.fragment_container, new LoginFragment())

            .commit();

}

(A).  Android FragmentManager

A FragmentManager manages Fragments in Android, specifically it handles transactions between fragments. A transaction is a way to add, replace, or remove fragments.
(B).  getFragmentManager()
Return the FragmentManager for interacting with fragments associated with this activity.
(C).  FragmentTransaction
FragmentTransaction gives us methods to add, replace, or remove fragments in Android. It gives us an interface for interacting with fragments.
(D).  fragmentManager.beginTransaction()
Start a series of edit operations on the Fragments associated with this FragmentManager.
(E).  fragmentTransaction.add(arg1,arg2)
Add a fragment to the activity. We pass two argument in it.
arg1 - It is container layout of fragment where fragment will be visible.
 In above example - see activity_main.xml
    <RelativeLayout
       
android:layout_width="match_parent"
       
android:layout_height="370dp"
       
android:id="@+id/fragment_container"
       
android:layout_marginTop="30dp"
       
>    </RelativeLayout>
arg2 - It's call the fragment class object.
In above example - see MainActivity.java
LoginFragment loginFragment=new LoginFragment();
// First we create object of LoginFragment class and then pass
        fragmentTransaction.replace(R.id.fragment_container, loginFragment);
(F).  fragmentTransaction.replace(arg1,arg2)
Replace the current fragment with another.
For Argument  ( arg1,arg2) - check  fragmentTransaction.add(arg1,arg2)
(G).  fragmentTransaction.addToBackStack(null)
This method, addToBackOfStack(String name), adds this transaction to the back stack, this can be used so that Fragments are remembered and can be used again by the Activity
(H).  fragmentTransaction.commit( )
The method commit() schedules this transaction, this is not instantaneous; It is scheduled on the main thread to be done when the thread is ready.
Creating a Fragment
To create a fragment, you must create a subclass of Fragment (or an existing subclass of it). The Fragment class has code that looks a lot like an Activity. It contains callback methods similar to an activity, such as onCreate(), onStart(), onPause(), and onStop().
Usually, you should implement at least the following lifecycle methods:
The system calls this when creating the fragment. Within your implementation, you should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.
The system calls this when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI.
For example - see above  RegisterFragment.java, LoginFragment.
The system calls this method as the first indication that the user is leaving the fragment (though it does not always mean the fragment is being destroyed). This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back).

https://developer.android.com/images/fragment_lifecycle.png


There are also a few subclasses that you might want to extend, instead of the base Fragment class:
Displays a floating dialog. Using this class to create a dialog is a good alternative to using the dialog helper methods in the Activity class, because you can incorporate a fragment dialog into the back stack of fragments managed by the activity, allowing the user to return to a dismissed fragment.
Displays a list of items that are managed by an adapter (such as a SimpleCursorAdapter), similar to ListActivity. It provides several methods for managing a list view, such as the onListItemClick() callback to handle click events.
Displays a hierarchy of Preference objects as a list, similar to PreferenceActivity. This is useful when creating a "settings" activity for your application.


Adding fragment to activity - Static Fragment
Usually, a fragment contributes a portion of UI to the host activity, which is embedded as a part of the activity's overall view hierarchy. There are two ways you can add a fragment to the activity layout:
  • Declare the fragment inside the activity's layout file.
In this case, you can specify layout properties for the fragment as if it were a view. For example, here's the layout file for an activity with two fragments:

activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

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

    android:id="@+id/LinearLayout1"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"    >



   <fragment

       android:id="@+id/fragment1"

       android:name="sichlearning.example.com.testone.LoginFragment"

       android:layout_width="match_parent"

       android:layout_height="fill_parent"

       android:layout_weight="1" />

   <fragment

       android:id="@+id/fragment2"

       android:name="sichlearning.example.com.testone.RegisterFragment"

       android:layout_marginLeft="5sp"

       android:layout_width="match_parent"

       android:layout_height="fill_parent"

       android:layout_weight="1" />



</LinearLayout>
activity_register_fragment.xml
<?xml version="1.0" encoding="utf-8"?>

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

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical" >



    <TextView

        android:id="@+id/textView1"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"

        android:text="I m fragment ONE"

        android:gravity="center"

        android:background="#5eff6a"

        android:textAppearance="?android:attr/textAppearanceLarge" />



</LinearLayout>


activity_login_fragment.xml
-------------------------------------------------------------------------------------------






























Create a Fragment

To create a fragment you must do two things:
  • Create a Fragment class.
  • Create a Fragment layout XML file.

Create a Fragment Class

To create a Fragment class, create an ordinary Java class which extends android.app.Fragment. Here is an example:
import android.app.Fragment;
 
 
public class MyFragment extends Fragment {
 
}

onCreateView()

This Fragment subclass isn't doing anything yet. The MyFragment class needs to override the method onCreateView() inherited from Fragment in order to create the fragment's View which is to be displayed inside the activity the fragment is added to. Here is an example fragment onCreateView() implementation:
public class MyFragment extends Fragment {
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parentViewGroup,
                             Bundle savedInstanceState) {
 
        View rootView = inflater.inflate(R.layout.fragment_my, parentViewGroup, false);
        return rootView;
    }
}
The onCreateView() method gets a LayoutInflater, a ViewGroup and a Bundle as parameters.
The LayoutInflater is an component which can create View instance based on layout XML files. As you can see, the example actually does that by calling layout.inflate() .
The inflate() method takes three parameters: The id of a layout XML file (inside R.layout), a parent ViewGroup into which the fragment's View is to be inserted, and a third boolean telling whether the fragment's View as inflated from the layout XML file should be inserted into the parent ViewGroup. In this case we pass false because the View will be attached to the parent ViewGroup elsewhere, by some of the Android code we call (in other words, behind our backs). When you pass false as last parameter to inflate(), the parent ViewGroup is still used for layout calculations of the inflated View, so you cannot pass null as parent ViewGroup .
The ViewGroup parameter of onCreateView() is the parent ViewGroup into which the View of the fragment is to be inserted. This is a ViewGroup inside the activity that will "host" the fragment.
The Bundle parameter of onCreateView() is a Bundle into which the fragment can save information, just like an Activity can.
















22



No comments:

Post a Comment