I am new in android. I often use Activity to change from one screen to another screen with other function. Example from Home Page to Popular page. After that, i know about fragment but i never use it before. So, if i have a application with multi tab on a screen, not use TabHost here. Function of every tab very diffrent, ex : tab Home, tab Popular, tab News, tab Profile ... like Instagram App. I must use that
What way is better ? I want to ask when use only phone screen. ( small size screen, not for tablet).
It's important to think of Android devices as more of a spectrum, than clear "phone" vs. "tablet" buckets. There are many instances where you might want to show more information on screen on medium
and large
screens. Sometimes, this translates to showing two "Activities" at once.
Using Fragments requires little overhead, but adds measurable flexibility, especially when considered early in the development process. If you use Fragments properly, adapting to larger screens is extremely simple. However, there are a few "gotchas" that may make Fragments appear to be more daunting that they actually are:
Fragment
classes must always be declared public
(if it's a nested class, it must be static
).
In the parent Activity
(or FragmentActivity
), only add the root Fragment
if savedInstanceState == null
. If you are managing the state of your Fragment
properly, everything is handled for you (scroll position, EditText values, etc).
The parent Activity
must call through to onSavedInstanceState
in order for the Fragment
to properly restore it's state.
setRetainInstance(true)
should only be used for "headless" Fragments. This is when you use a Fragment that has no UI, and isn't added to the back stack, which is typically used to do life-cycle dependent work.
Fragments declared in XML cannot be used in a FragmentTransaction
(and vice-versa).
Think of a Fragment
as a modular view, that provides hooks (callbacks) to it's Activity
when something important happens. The Activity
decides, based on the available space, whether to launch a new Activity
, or show a new Fragment
.
You can use either way. If you decide to use the Activity solution, create a base activity class that contains all the Tab functionality. You don't want to implement that in every Activity over and over again.
public class BaseActivity extends Activity {
@Override
public void onCreate(...) {
// Init tabs
}
// Methods for tab handling
}
Every Activity (Popular, Profile, Home, ...) extends BaseActivity
public class PopularActivity extends BaseActivity {
@Override
public void onCreate(...) {
super.onCreate(...);
// Init only the popular activity elements here
}
}
This way you implement the tab functionality only once and get it in every activity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With