fragmentacitivty

13
Mobile Application Development FragmentActivity 1

description

fragmentacitivty

Transcript of fragmentacitivty

Course Title

Mobile Application DevelopmentFragmentActivity1IntroductionCreating a dynamic and multi-pane user interface on Android, need to encapsulate UI components and activity behaviors into modules that you can swap into and out of your activities.Fragment class can be used to create these modules, which behaves somewhat like a nested activity that can define its own layout and manage its own lifecycle.It represents a behavior or a portion of user interface in an Activity.2IntroductionDeveloper can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. Fragment can be considered as a modular section of an activity, which has its own lifecycle, receives its own input eventsFragment can be added or removed while the activity is running Fragment introduced primarily to support more dynamic and flexible UI designs on large screens, such as tablets.

3tablet's screen is much larger than that of a handset, there's more room to combine and interchange UI components.

Introduction4

Fragment Support LibraryThe Support Library provides a version of the Fragment APIs that you can use on Android 1.6 (API level 4) and higher.Adding Support library to projectRight click-> Android tools -> Add Support LibraryTo be sure that you don't accidentally use new APIs on an older system version, import the Fragment class and related APIs from the android.support.v4.app package:import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;

5Using FragmentsThe main activity must extends the FragmentActivity class

The main activitys layout should has a space, ViewGroup, to display the fragmentsIf there is more than one fragment appropriate way must be used to call these fragments

The fragment activity must extends the Fragment classAlso all the other fragment activities too.

Dont forget that the fragment activity has its own lifecycle.6Using FragmentsIn the MainActivity, do the following steps:Create a FragmentManager fmgr"returned by getSupportFragmentManager()Create a FragmentTransaction ftransreturned by fmgr. beginTransaction();Add fragment object to FragmentTransaction ftrans.add(R.id.fragContainer, FragObj);Commit the FragmentTransaction to start the fragment.ftrans.commit();7Using FragmentsMainActivity

public class MainActivity extends FragmentActivity {@Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FragmentManager fmgr = getSupportFragmentManager(); FragmentTransaction ftrans = fmgr.beginTransaction(); StartFragment startFrag = new StartFragment(); ftrans.add(R.id.fragContainer, startFrag); ftrans.commit(); } //handling fragments switching by using //selectFragment method}8Using FragmentsfragmentActivity