Friday 29 August 2014

Android: Fragment demo to Add & Replace fragment, Different UI for different orientation.

Please visit my website for latest post about the difference between Add & Replace method and use of Back Stack.

http://dipenpatel.co.in/understanding-android-fragmentsadd-replace-method-and-back-stack/




Adding here Fragment demo which "Add" & "Replace" fragment in fragment holder.

Adding demo app for::

  • Fragment
  • Add & Replace fragment
  • Different UI for different orientation
  • Maintaining BackStack of Fragment






                           1. Portrait UI                                        2. Lanscape UI

We will add different layout xml in different layout folder "layout" & "layout-land" to render differently on different orientation.

There are two Fragment & two Button, first button will "Replace" first fragment container and second button will "Add" fragment in second fragment container.

When we "Replace" fragment it will detach existing fragment and "Add" new fragment.
When we "Add" fragment it will add new fragment and existing fragment remain same.

We can maintain back stack of fragment which can be accessible later.
  /**
   * We can add name to this back stack and we can access this fragment by name later.
     Otherwise we can pass null to parameter*/
    fragmentTwoTransaction.addToBackStack(null);  

Note:
I have added every fragment method name in StringBuilder when this method execute and Toast this StringBuilder onDetach of fragment. You can uncomment the Toast line in onDetach method and check fragment lifecycle.

About Code:::

LauncherActivity.java

/**
 * @author dipenp
 *
 */
public class LauncherActivity extends Activity {

private Button replaceFragmentButton, addFragmentButton;
private static int FRAGMENT_ONE_POSITION = 0, FRAGMENT_TWO_POSITION = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

/**************************************************
* Adding layout with two Button & two Fragment.
* One button to "Replace" fragment in first fragment & one button to "Add" fragment in second fragment.
* We have added same layout with different structure in different folder one in layout & one in layout-land(to display when device in landscape mode)
**************************************************/
setContentView(R.layout.activity_launcher);

replaceFragmentButton = (Button)findViewById(R.id.buttonOne);
addFragmentButton = (Button)findViewById(R.id.buttonTwo);

/**
* When we click on this button it will "Replace" existing fragment and add new one.
*/
replaceFragmentButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
FragmentTransaction fragmentOneTransaction = getFragmentManager().beginTransaction();

switch (FRAGMENT_ONE_POSITION) {
case 0:
FRAGMENT_ONE_POSITION++;
fragmentOneTransaction.replace(R.id.fragment_one_holder, new FragmentOne(LauncherActivity.this));
break;
case 1:
FRAGMENT_ONE_POSITION++;
fragmentOneTransaction.replace(R.id.fragment_one_holder, new FragmentTwo(LauncherActivity.this));
break;
case 2:
FRAGMENT_ONE_POSITION = 0;
fragmentOneTransaction.replace(R.id.fragment_one_holder, new FragmentThree(LauncherActivity.this));
break;
default:
break;
}

// fragmentOneTransaction.addToBackStack(null);
fragmentOneTransaction.commit();
}
});


/**
* When we click on this button it will "Add" new fragment.
*/
addFragmentButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
FragmentTransaction fragmentTwoTransaction = getFragmentManager().beginTransaction();

switch (FRAGMENT_TWO_POSITION) {
case 0:
FRAGMENT_TWO_POSITION++;
fragmentTwoTransaction.add(R.id.fragment_two_holder, new FragmentOne(LauncherActivity.this));
break;
case 1:
FRAGMENT_TWO_POSITION++;
fragmentTwoTransaction.add(R.id.fragment_two_holder, new FragmentTwo(LauncherActivity.this));
break;
case 2:
FRAGMENT_TWO_POSITION = 0;
fragmentTwoTransaction.add(R.id.fragment_two_holder, new FragmentThree(LauncherActivity.this));
break;
default:
break;
}

/**
* Adding current fragment to back stack which can be pop back when we need.
* We can add name to this back stack and we can access this fragment by name later.
*/
fragmentTwoTransaction.addToBackStack(null);
fragmentTwoTransaction.commit();
}
});
}

/**************************************
* Overriding onBackPressed button and pop backStack fragment.
*
**************************************/
@Override
public void onBackPressed() {
FragmentManager fm = getFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
} else {
super.onBackPressed();
}
}

}

You can download demo code from below url:
https://drive.google.com/file/d/0B0mH97AUwQqhMXVkc0N6VkY0cGM/edit?usp=sharing





66 comments:

  1. Digital marketing course in Noida - Digital Marketing is a broad term that includes advertising, promoting, and strengthening the online presence of businesses through digital platforms. Some of the digital tactics that fall under the umbrella of 'Digital Marketing' are digital advertising, email marketing, content marketing, pay-per-click, online brochures, and more. Unlike other offline marketing efforts, digital marketing allows getting accurate results in real time. For example, if you put an advertisement in the newspaper, it is nearly impossible to estimate how many people flipped to that page and paid attention to that ad. Digital marketing training in Noida

    ReplyDelete
  2. Access different forms of check out logs and send metadata and enterprise facts the commercial enterprise official, nature of the career and the issues skilled with the aid of the enterprise strength.
    Because of excessive demand of Salesforce in marketplace, you may find many training institutes providing Salesforce Training in Noida. However it required to find best in elegance training centre .There are numerous top level features for a worth training .Therefore, a very a great deal composed training software cannot be changed overnight as it calls for range of productive making plans ,setting it up, introducing it, operating it and assessing it.

    ReplyDelete
  3. SFDC Training path is supposed to assure which you study and enforce the thoughts of SFDC platform developer and bypass any required accreditation checks on your first attempt. Quality in elegance guidance will assist you spot how to make bigger salesforce highlights utilizing the state-of-the-art and automated abilities of SFDC code and visual pressure. The down to earth fingers-on mastering approach observed within the route will assure you land role prepared earlier than the cease of it. For best Salesforce Training in Noida aspirants needs to get training from authorised centre for ultimate solutions. Salesforce training in noida sector 63

    ReplyDelete
  4. Android training center in noida sector 15 Android is an open source and Linux-based Operating System Android is an open source and Linux-based Operating System for PDAs, for instance, mobile phones and tablet PCs. Android was made by the Open Handset Alliance, drove by Google, and distinctive associations. Android training in noida Webtrackker Technology offers a united approach to manage application headway for mobile phones which suggest engineers require create for Android, and their applications should have the ability to continue running on different contraptions controlled by Android.

    ReplyDelete
  5. Android training center in noida sector 15 Android is an open source and Linux-based Operating System Android is an open source and Linux-based Operating System for PDAs, for instance, mobile phones and tablet PCs. Android was made by the Open Handset Alliance, drove by Google, and distinctive associations. Android training in noida Webtrackker Technology offers a united approach to manage application headway for mobile phones which suggest engineers require create for Android, and their applications should have the ability to continue running on different contraptions controlled by Android.

    ReplyDelete
  6. Android, MAC & Phone gap is the most popular operating system using in tablet iPhone & smarts phone. Because of the rising the request and high offering of Apps based mobile devices, demanding of smart phone in the market is being going up step by step. The most reason of requesting this is Android is user friendly environment means that simple to use as contrast with other working frameworks in savvy phone.

    ReplyDelete
  7. Android, MAC & Phone gap is the most popular operating system using in tablet iPhone & smarts phone. Because of the rising the request and high offering of Apps based mobile devices, demanding of smart phone in the market is being going up step by step. The most reason of requesting this is Android is user friendly environment means that simple to use as contrast with other working frameworks in savvy phone.

    ReplyDelete
  8. Android, MAC & Phone gap is the most popular operating system using in tablet iPhone & smarts phone. Because of the rising the request and high offering of Apps based mobile devices, demanding of smart phone in the market is being going up step by step. The most reason of requesting this is Android is user friendly environment means that simple to use as contrast with other working frameworks in savvy phone.

    ReplyDelete
  9. Android, MAC & Phone gap is the most popular operating system using in tablet iPhone & smarts phone. Because of the rising the request and high offering of Apps based mobile devices, demanding of smart phone in the market is being going up step by step. The most reason of requesting this is Android is user friendly environment means that simple to use as contrast with other working frameworks in savvy phone.

    ReplyDelete
  10. Android, MAC & Phone gap is the most popular operating system using in tablet iPhone & smarts phone. Because of the rising the request and high offering of Apps based mobile devices, demanding of smart phone in the market is being going up step by step. The most reason of requesting this is Android is user friendly environment means that simple to use as contrast with other working frameworks in savvy phone.
    The applications programming designers need to much consider a long series of screen sizes, hardware specifications and configurations due to strong competition in the mobile software and changes within each of the platforms. The development of mobile applications is always developing, both as far as wage and jobs created.

    ReplyDelete
  11. Android, MAC & Phone gap is the most popular operating system using in tablet iPhone & smarts phone. Because of the rising the request and high offering of Apps based mobile devices, demanding of smart phone in the market is being going up step by step. The most reason of requesting this is Android is user friendly environment means that simple to use as contrast with other working frameworks in savvy phone.
    The applications programming designers need to much consider a long series of screen sizes, hardware specifications and configurations due to strong competition in the mobile software and changes within each of the platforms. The development of mobile applications is always developing, both as far as wage and jobs created.

    ReplyDelete
  12. Initially, Andy Rubin set up Android Incorporation in Palo Alto, California, United States in October, 2003. In seventeenth August 2005, Google secured android Incorporation. Beginning now and into the not too far-removed, it is in the support of Google Incorporation. The key administrators of Android Incorporation are Andy Rubin, Rich Miner, Chris White and Nick Sears. Originally proposed for camera yet moved to cutting edge PDAs later in this way of low market for camera in a way. Android is the moniker of Andy Rubin given by partners by respectability of his affection to robots. In 2007, Google reports the progress of OS. In 2008, HTC moved the key android adaptable.

    ReplyDelete
  13. Initially, Andy Rubin set up Android Incorporation in Palo Alto, California, United States in October, 2003. In seventeenth August 2005, Google secured android Incorporation. Beginning now and into the not too far-removed, it is in the support of Google Incorporation. The key administrators of Android Incorporation are Andy Rubin, Rich Miner, Chris White and Nick Sears. Originally proposed for camera yet moved to cutting edge PDAs later in this way of low market for camera in a way. Android is the moniker of Andy Rubin given by partners by respectability of his affection to robots. In 2007, Google reports the progress of OS. In 2008, HTC moved the key android adaptable.

    ReplyDelete
  14. I wanted to thank you for this excellent read!! I definitely loved every little bit of it. I have you bookmarked your site to check out the new stuff you post. Viking Freezer Repair in Los Angeles

    ReplyDelete
  15. I wanted to thank you for this excellent read!! I definitely loved every little bit of it. I have you bookmarked your site to check out the new stuff you post. Sub-Zero PRO 48 Refrigerator Repair

    ReplyDelete
  16. http://webtrackker.com/Best-institute-for-uipath-training-course-in-Noida.php
    http://www.webtrackker.com/SAP_SCM_SD_SRM_Training_in_Noida.php
    http://www.webtrackker.com/course/Best-Android-Apps-training-institute-center-in-Noida-sector-15.php
    http://webtrackker.com/course/Best-linux-training-institute-center-in-noida-sector-15.php
    http://webtrackker.com/course/Best-linux-training-institute-center-in-noida-sector-62.php
    http://webtrackker.com/course/Best-linux-training-institute-center-in-noida-sector-63.php

    ReplyDelete
  17. After understanding what the number one factors of DevOps are, you get to well known about the cultural movement it wants to awareness on for a higher illustration of the company. Let us observe about the precise cultures that it looks after: As with the aid of the name of DevOps is named, it shows a collaboration of improvement and operations. Thus, other than this you also want to collaborate certain other functions which make the work more precise, powerful and green. The collaboration additionally includes an amalgamation of product control and other factors. Automation is one of the key components of automation. Quite apparently it is the distinct tools which you need to expand the specific prospectus. DevOps depends on those open-source gear to revert to quit-to-cease variant software for powerful delivery. Many professionals also can relate this to a group of equipment inside the procedure. DevOps growing agile stories want to have this continuous integration that constantly amalgamates the supply code and updates them from all originators into a collective mainline. This incessant merging averts a developer's indigenous copy of the assignment from migrating too a long way. This is due to the fact a brand new code is generated and supplemented by others, evading cataclysmic merge conflicts. This seed blooms for the satisfactory way of life in DevOps

    WEBTRACKKER TECHNOLOGY (P) LTD.
    B - 85, sector- 64, Noida, India.
    E-47 Sector 3, Noida, India.
    +91 - 8802820025
    0120-433-0760
    +91 - 8810252423
    012 - 04204716
    EMAIL: info@webtrackker.com
    data science training center in noida
    data science training in noida

    ReplyDelete
  18. As per requirement of ECommerce developer and product photographer the carrier could be finished. Most of the eCommerce web page like Amazon, E bay, Alibaba, Ali express have pick out the heritage Reomoval for branding their product. Clipping route provider should be performed on the idea of picture law. Because the pix designer always don't forget the law of image for slicing, cropping and disposing of history to make a high-quality photograph. Although we will select the photograph history elimination area by means of vehicle choice device but it damages the picture excellent. To make certain 100% first-class product photo you have to must use Path equipment or clipping direction carrier. Actuality the service relies upon at the creativity of the graphics dressmaker. At the age of Information Technology may be very vital for enterprise advertising. Usually the enterprise entrepreneurs are desired to branding their product as graphical interface. Because we are able to without problems present the substantial information by way of graphical interface very shorten manner. As a result the call for of product pictures is growing each day for photograph marketing. One of the pleasant gear for product images. Now a day the product photographer asking clipping service from a pics fashion designer for branding the photo photographs. So the clipping service has end up a aggressive time period for product images advertising and in addition to enterprise promotion.

    WEBTRACKKER TECHNOLOGY (P) LTD.
    B - 85, sector- 64, Noida, India.
    E-47 Sector 3, Noida, India.
    +91 - 8802820025
    0120-433-0760
    +91 - 8810252423
    012 - 04204716
    EMAIL: info@webtrackker.com

    ReplyDelete
  19. Time sharing pay endeavors to consciousness on the antique and the new-account control. When working with new customers within the mission have to moreover hold vintage customers likewise manage dissatisfied customers with an astounding wide collection of following offerings. Field kind applied is predicated upon the scale of your association. On the off hazard that you need to make use of the type of skill to earnings effect, explicitly wonderful enterprise venture businesses must pick. On the off danger that that is the type of inquiries weaving up inside the manage of the pay stress to test the complete issue. Deals the board and tutoring of group of workers and the pleasant of your own willpower has a part of the vender, which includes in popular execution, upgrade the presentation of power use inside the diverse tactics of thought. After the deal, and the complete above situation, the check weight and a triumph calling in CRM. Field kind utilized relies upon upon at the additives of your enterprise undertaking. In the event that that is the kind of inquiries weaving up within the administration of the earnings electricity to test the entirety. For future revolutionary patterns and the superior media of the Organization, permitting the creation of extra clients on the earliest possibility. Deals manipulate and getting ready of institution of workers and the great of your own one in every of a kind decision has a number of the seller, comprehensive of by using and big execution, enhance the exhibition of energy use inside the one-of-a-kind systems of idea. After the deal, and the entire above scenario, the check weight and a triumph profession in CRM.If you need to run pleasantly, precise goals, it ought to be each one of the approach which might be a chunk of revenue the executives is finished effectively.


    WEBTRACKKER TECHNOLOGY (P) LTD.
    B - 85, sector- 64, Noida, India.
    E-47 Sector 3, Noida, India.
    +91 - 8802820025
    0120-433-0760
    +91 - 8810252423
    012 - 04204716
    EMAIL: info@webtrackker.com

    ReplyDelete
  20. devops training in noida

    Ui Path training center in Noida

    salesforce training in noida sector 18

    salesforce training in noida sector 62

    salesforce training in noida sector 63

    salesforce training in noida sector 64

    digital marketing training center in noida sector 16

    digital marketing training center in noida sector 15

    digital marketing training center in noida sector 18

    linux training center in noida sector 15

    linux training center in noida sector 62

    linux training center in noida sector 63

    android training center in noida sector 62

    android training center in noida sector 15

    ReplyDelete
  21. Time sharing pay endeavors to consciousness on the antique and the new-account control. When working with new customers within the mission have to moreover hold vintage customers likewise manage dissatisfied customers with an astounding wide collection of following offerings. Field kind applied is predicated upon the scale of your association. On the off hazard that you need to make use of the type of skill to earnings effect, explicitly wonderful enterprise venture businesses must pick. On the off danger that that is the type of inquiries weaving up inside the manage of the pay stress to test the complete issue. Deals the board and tutoring of group of workers and the pleasant of your own willpower has a part of the vender, which includes in popular execution, upgrade the presentation of power use inside the diverse tactics of thought. After the deal, and the complete above situation, the check weight and a triumph calling in CRM. Field kind utilized relies upon upon at the additives of your enterprise undertaking. In the event that that is the kind of inquiries weaving up within the administration of the earnings electricity to test the entirety. For future revolutionary patterns and the superior media of the Organization, permitting the creation of extra clients on the earliest possibility. Deals manipulate and getting ready of institution of workers and the great of your own one in every of a kind decision has a number of the seller.

    WEBTRACKKER TECHNOLOGY (P) LTD.
    B - 85, sector- 64, Noida, India.
    E-47 Sector 3, Noida, India.
    +91 - 8802820025
    0120-433-0760
    +91 - 8810252423
    012 - 04204716
    EMAIL: info@webtrackker.com

    ReplyDelete
  22. Time sharing pay endeavors to consciousness on the antique and the new-account control. When working with new customers within the mission have to moreover hold vintage customers likewise manage dissatisfied customers with an astounding wide collection of following offerings. Field kind applied is predicated upon the scale of your association. On the off hazard that you need to make use of the type of skill to earnings effect, explicitly wonderful enterprise venture businesses must pick. On the off danger that that is the type of inquiries weaving up inside the manage of the pay stress to test the complete issue. Deals the board and tutoring of group of workers and the pleasant of your own willpower has a part of the vender, which includes in popular execution, upgrade the presentation of power use inside the diverse tactics of thought. After the deal, and the complete above situation, the check weight and a triumph calling in CRM. Field kind utilized relies upon upon at the additives of your enterprise undertaking. In the event that that is the kind of inquiries weaving up within the administration of the earnings electricity to test the entirety. For future revolutionary patterns and the superior media of the Organization, permitting the creation of extra clients on the earliest possibility. Deals manipulate and getting ready of institution of workers and the great of your own one in every of a kind decision has a number of the seller.

    WEBTRACKKER TECHNOLOGY (P) LTD.
    B - 85, sector- 64, Noida, India.
    E-47 Sector 3, Noida, India.
    +91 - 8802820025
    0120-433-0760
    +91 - 8810252423
    012 - 04204716
    EMAIL: info@webtrackker.com

    ReplyDelete
  23. Android primarily based Smartphones have seized the attention of the neighborhood in addition to international marketplace. The addiction is in particular because of the applications this smarty smartphone comes loaded with. The patron demand for specific and thrilling cell packages is at peak; in reality this demand has obtained middle degree. As a end result, Android utility development has carved a wealthy and booming photograph for each humunoid developers and organizations. This platform has helped expand many particular apps for special classes like finance, leisure, media, sports, utilities, climate, news, navigation, banking, business and others. With the emergence of the precise concept of corporation mobility answers, even groups can harness the benefits of first-rate Android app improvement. They have the rights to effortlessly personalize the programs developed the usage of this platform. Initially, a few problems of safety breach were found. However, those threats have no longer been eliminated with using cutting-edge and complicated generation improvements. This guarantees that humanoid apps are much less vulnerable to threats and are secured in nature. Smartphones have turn out to be a not unusual tool to connect human beings from throughout the globe in many methods, thru chat, immediately and text messages, audio visual call, name conferencing and others. The Android platform is showing no signs and symptoms of slowing down. The quantity of apps produced and taken to marketplace each day is rising continuously.
    Android is an open source platform, which cuts the improvement value then and there. It is an cheap manner and most importantly does not restrict the improvement procedure with the license rate. Yes, Android does no longer require any license. If you are making plans for inter application integration, Android is exceptional suitable for it. It permits improvement of custom applications for on line shops.

    WEBTRACKKER TECHNOLOGY (P) LTD.
    B - 85, sector- 64, Noida, India.
    E-47 Sector 3, Noida, India.
    +91 - 8802820025
    0120-433-0760
    +91 - 8810252423
    012 - 04204716
    EMAIL: info@webtrackker.com

    ReplyDelete
  24. Android primarily based Smartphones have seized the attention of the neighborhood in addition to international marketplace. The addiction is in particular because of the applications this smarty smartphone comes loaded with. The patron demand for specific and thrilling cell packages is at peak; in reality this demand has obtained middle degree. As a end result, Android utility development has carved a wealthy and booming photograph for each humunoid developers and organizations. This platform has helped expand many particular apps for special classes like finance, leisure, media, sports, utilities, climate, news, navigation, banking, business and others. With the emergence of the precise concept of corporation mobility answers, even groups can harness the benefits of first-rate Android app improvement. They have the rights to effortlessly personalize the programs developed the usage of this platform. Initially, a few problems of safety breach were found. However, those threats have no longer been eliminated with using cutting-edge and complicated generation improvements. This guarantees that humanoid apps are much less vulnerable to threats and are secured in nature. Smartphones have turn out to be a not unusual tool to connect human beings from throughout the globe in many methods, thru chat, immediately and text messages, audio visual call, name conferencing and others. The Android platform is showing no signs and symptoms of slowing down. The quantity of apps produced and taken to marketplace each day is rising continuously.
    Android is an open source platform, which cuts the improvement value then and there. It is an cheap manner and most importantly does not restrict the improvement procedure with the license rate. Yes, Android does no longer require any license. If you are making plans for inter application integration, Android is exceptional suitable for it. It permits improvement of custom applications for on line shops.

    WEBTRACKKER TECHNOLOGY (P) LTD.
    B - 85, sector- 64, Noida, India.
    E-47 Sector 3, Noida, India.
    +91 - 8802820025
    0120-433-0760
    +91 - 8810252423
    012 - 04204716
    EMAIL: info@webtrackker.com

    ReplyDelete
  25. http://webtrackker.com/course/Best-AWS-training-institute-center-in-ghaziabad.php
    Python Training Institute in Noida
    Solidworks Training Institute in Noida
    Hadoop training institute in Noida
    SAP FICO Training Institute in Noida
    AWS Training Institute in Noida
    AutoCAD Training Institute In Noida
    Linux Training Institute In Noida
    Data Science With python training Institute in Noida
    SAS Training Institute in Noida
    6 weeks industrial training in noida
    machine learning training Institute in Noida
    salesforce training institute in noida
    php training institute in noida
    uipath training institute in noida
    Data Science training Institute in Noida
    sap training institute in noida
    azure training institute in noida
    sap mm training institute in noida
    web designing institute in noida
    AWS Training course in Noida
    AWS Training center in Noida
    Python Training course in Noida
    Python Training center in Noida
    Hadoop training course in Noida
    Hadoop training center in Noida
    SAP FICO Training course in Noida
    SAP FICO Training center in Noida
    Linux Training course In Noida
    Linux Training center In Noida
    SAS Training course in Noida
    SAS Training center in Noida
    Machine learning training course in Noida
    Machine learning training center in Noida
    Solidworks Training course in Noida
    Solidworks Training center in Noida
    cloud computing training in noida
    oracle training in noida
    oracle training center in noida
    sql training center in noida
    best sql training in noida
    best pl sql training in noida
    node js training in noida
    angular 6 training in noida
    angularjs training in noida
    mean stack training in noida
    digital marketing training in noida
    digital marketing training center in
    noida
    blue prism training center in noida

    ReplyDelete
  26. Casinos Near Atlanta, GA - MapYRO
    Find Casinos Near Atlanta, 군포 출장마사지 GA in realtime and see activity. 의정부 출장마사지 Realtime driving 광명 출장샵 directions to casinos, compare current and historic Casinos, see 파주 출장샵 activity. 성남 출장안마

    ReplyDelete
  27. Our SolidWorks Course in Noida is designed to provide hands-on training, enabling students to master the software's various functionalities, from 2D sketching to 3D modeling and simulations. With our experienced and certified instructors, you will learn to create intricate designs, assemble components, and perform simulations to ensure the viability of your projects. This practical approach ensures that you graduate with not just theoretical knowledge but also the ability to apply SolidWorks effectively in real-world scenarios.

    ReplyDelete