android - Am I using fragments right? -
i bit confused ideologically correct way of using fragments.
as android developers states,
a fragment represents behavior or portion of user interface in activity. can combine multiple fragments in single activity build multi-pane ui , reuse fragment in multiple activities. can think of fragment modular section of activity, has own lifecycle, receives own input events, , can add or remove while activity running (sort of "sub activity" can reuse in different activities).
and also:
fragments decompose application functionality , ui reusable modules add multiple fragments screen avoid switching activities
and usage of fragments goes following way: have 1 main activity , whole bunch of fragments. instead of starting activities, prefer replacing fragments. example, have feedsfragment
, friendsfragment
, messagesfragment
, , when select sliding menu, activity
replaces main fragment
. if i'm launching fragment other fragment, put previous 1 in backstack.
some fragments require activity change actionbar, directly by
((mainactivity)getactivity()).setupactionbar();
currently don't have code supports tablet layouts (as seen in examples on android developers), i'm planning add it.
so, right way of doing things? or missing something?
as know fragment has own lifecycle, , can use event when ever want activity lifecyle.
but fragments lifecycle depens on activity lifecycle when actvity destroyed, fragments destroyed also.
// create new fragment , transaction fragment newfragment = new examplefragment(); fragmenttransaction transaction = getfragmentmanager().begintransaction(); // replace whatever in fragment_container view fragment, // , add transaction stack transaction.replace(r.id.fragment_container, newfragment); transaction.addtobackstack(null); // commit transaction transaction.commit();
yo can use fragment transaction, replace them in 1 activity, think use same way,
i think arent wrong way , there no problem use fragment instead of using different activites.
but should think about, realy need use them in 1 activty ? if dont need show them in 1 activity dont need use fragment.
a fragment must embedded in activity , fragment's lifecycle directly affected host activity's lifecycle. example, when activity paused, fragments in it, , when activity destroyed, fragments. however, while activity running (it in resumed lifecycle state), can manipulate each fragment independently, such add or remove them. when perform such fragment transaction, can add stack that's managed activity—each stack entry in activity record of fragment transaction occurred. stack allows user reverse fragment transaction (navigate backwards), pressing button.
as result , not wrong , think if dont need, creating different activity easy maintain.
Comments
Post a Comment