Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fragment_main and activity_main layouts in Android Studio

I am confused with the two layout files that are generated by the Android Studio. (fragment_main.xml and activity_main.xml)

I use activity_main.xml. To use activity_main.xml I need to comment out

if(savedInstanceState==null){...} //in onCreate(), Otherwise it will not display

Then I can use activity_main.xml.

Can some one explain me

  1. when to use Fragment_main.xml

  2. Advantage of using both layouts.

  3. How to use them correctly.(If I do not comment out above line it will not display activity_main.xml, instead it shows fragment_main layout. That means I need to create the interface in the fragment_main.xml.)

Thanks.

like image 813
chathura Avatar asked Jan 16 '14 05:01

chathura


1 Answers

Following are the benefits using Fragments(Fragmenting your Activities) :

  1. Multiple mode supports : Like if your application supports landscape and portrait mode or tablet devices. Consider something like you have a list view and another is the details page in your app. You can make two fragments one with list view and one with details instead of two activities and can group together in landscape and in tablet devices instead of making an another activity for tablet. Have a look on android Settings screen in tablet.

  2. Custom Views : There are some scenarios where we need to create some custom views but the issue with custom views are maintaining the state so instead you can use fragment if they fits in your needs.

  3. App Navigation : Sliding drawer navigation handling. Open Google Play in your device an check the sliding navigation. If you tap on any of the option available in sliding navigation bar, you wont see any activity started on tapping on the items. As they all are top view of app,in such scenarios you can have an Activity with fragment and change them on tap .

  4. Reuse the views : Once you Create your Fragment you can use them in any activity at run time attaching them in your activity.

There are many other benefits, you will find them once you start using.

There is a nice explanation over here on android developer's space :

http://developer.android.com/guide/components/fragments.html

Read this and decide.

like image 193
Piyush Agarwal Avatar answered Sep 29 '22 20:09

Piyush Agarwal