Skip to main content

Fragments in Android

Fragment   is a piece of an activity which enable more modular activity design. It will not be wrong if we say, a Fragment is a kind of sub-activity.
A Fragment represents a behavior or a portion of user interface in an activity. You can combine 
multiple fragments in a single activity yo 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.
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. 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. However, a fragment is not required to be a part of the activity layout; you may also use a fragment without its own UI as an invisible worker for the activity.
 Example:-   
Here I Created simple Example how we are using Fragments in an Activity an how  make Transaction between Activity and a Fragment in Android 
Create method inside the main activity name as   Loadfragment
 
public void Loadfragment(Fragment fragment){
 // create a FragmentManager 
 FragmentManager fragmentManager= getFragmentManager();
  // create a FragmentTransaction to begin the transaction and replace the Fragment 
 FragmentTransaction fragmentTransaction= fragmentManager.beginTransaction();
  if(fragmentTransaction==null){
    fragmentTransaction.add(R.id.frameLayout,fragment);
  }else {
    // replace the FrameLayout with new Fragment 
   fragmentTransaction.replace(R.id.frameLayout, fragment);
  }
  fragmentTransaction.commit(); // save the changes}
This method  takes the name of fragment  as a parameter which you can add inside the Activity.
Call this method inside the Activity onCreate() Method   for adding fragment  first inside the
Activity when it will open  Like:-
public class MainActivity extends AppCompatActivity {
  private TextView mTextMessage;
  private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener  = new BottomNavigationView.OnNavigationItemSelectedListener() {

  @Override
  public boolean onNavigationItemSelected(@NonNull MenuItem item) {
  switch (item.getItemId()) {
  case R.id.navigation_home:
  Loadfragment(new Fragmentfirst());
  return true;
  case R.id.navigation_dashboard:
  Loadfragment(new FragmentSecond());
  return true;
  case R.id.navigation_notifications:
  Loadfragment(new FragmentThird());
  return true;
}
return false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
  navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
  Loadfragment(new Fragmentfirst());
}
public void Loadfragment(Fragment fragment){
  // create a FragmentManager   
FragmentManager fragmentManager= getFragmentManager();
  // create a FragmentTransaction to begin the transaction and replace the Fragment   
FragmentTransaction fragmentTransaction= fragmentManager.beginTransaction();
  if(fragmentTransaction==null){
     fragmentTransaction.add(R.id.frameLayout,fragment);
  }else {
    // replace the FrameLayout with new Fragment     
    fragmentTransaction.replace(R.id.frameLayout, fragment);
  }
  fragmentTransaction.commit(); // save the changes}

}
  
XML File
<android.support.constraint.ConstraintLayout 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:id="@+id/container" 
 android:layout_width="match_parent"
 android:layout_height="match_parent"tools:context="com.ss.fragmentexanple.MainActivity">
<FrameLayout
    android:id="@+id/frameLayout" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"
    android:layout_marginBottom="55dp" />
<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="0dp" 
    android:layout_height="wrap_content"
    android:layout_marginEnd="0dp" 
    android:layout_marginStart="0dp"
    android:background="?android:attr/windowBackground"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent" 
    app:layout_constraintRight_toRightOf="parent" 
    app:menu="@menu/navigation" />
</android.support.constraint.ConstraintLayout>

 Create Three  Fragments named as Fragmentfirst,FragmentSecond,FragmentThird
 For Create Fragment  follow the steps :-
1. click on File->New->Fragment->Fragment(Blank)

Source Code Download link:-https://drive.google.com/open?id=10z-FF7PsH5acjFSTBGL1vLqm99IoK0rl



 
 


 


 


Comments

Popular posts from this blog

How to align Title at center of ActionBar in Android

How to Align Title At Center of Action Bar in Android                                                                                                                                                @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setTitle("DashBoard"); }   Activity  public void setTitle ( String title ){ getSupportActionBar (). setHomeButtonEnabled ( true ); getSupportActionBar (). setDisplayHomeAsUpEnabled ( true ); TextView textView = new TextView ( this ); textView . setText ( title ); textView . setTextSize ( 20 ); textView . setTypeface ( null , Typeface . BOLD ); textView . setLayoutParams ( new LinearLayout . LayoutParams ( LinearLayout . LayoutParams . FILL_PARENT , LinearLayout . LayoutParams . WRAP_CONTENT )); textView . setGravity ( Gravity . CENTER ); textView . setTextColor ( getResources (). ge

Difference Between Pending Intent And Intent in Android

                       Normal Intent       Normal Intent will die as soon as the app being killed.    An Android Intent is an object carrying an intent, i.e a message from one Component to another     Component either inside or outside of the application.Intent can communicate message among     any of the three core Components of an application -- Activities, Services,and BroadcastReceivers.     Two types of Intent in Android   1. Explicit Intent.   2.Implicit Intent  Explicit Intent is an Intent which is used to Call the another component Explicitly in your application  Like :We are calling  Next activity on button click of First activity using Intent Example  // Explicit Intent by specifying its class name Intent i = new Intent ( this , TargetActivity . class ); i . putExtra ( "Key1" , "ABC" ); i . putExtra ( "Key2" , "123" ); // Starts TargetActivity startActivity ( i );  Implicit Intent Intent

Expected a key while parsing a block mapping (Flutter)

Flutter makes use of the Dart packaging system, pub. Via your applications  pubspec.yam l file (or simple pubspec), you can pull down packages from the flutter ecosystem, or the broader dart community. Anyway, i need to add some images to my flutter application, and so had to add an assets section to the pubspec .the default Android Studio generated apps pubspec has a lot of commented out code with explainations about what is going on, e.g # To add assets to your application, add an assets section, like this: # assets: # - images/a_dot_burr.jpeg # - images/a_dot_ham.jpeg # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.io/assets-and-images/#resolution-aware. So I uncommented these lines # assest : - - - #  -  images/a_dot_ham.jpeg with the idea from these comment.  that i would just edit it to suit my particular needs. Once you have edited your  pubspec, you need to click on the "Get dependencies"