What are the differences between activity and fragment?
Those are two completely different things:
An Activity is an application component that provides a screen, with which users can interact in order to do something. More details:
https://developer.android.com/guide/components/activities/intro-activities
Whereas a Fragment represents a behavior or a portion of user interface in an Activity.
https://developer.android.com/guide/fragments
Difference between Activity and FragmentActivity
A FragmentActivity
is a subclass of Activity
that was built for the Android Support Package.
The FragmentActivity
class adds a couple new methods to ensure compatibility with older versions of Android, but other than that, there really isn't much of a difference between the two. Just make sure you change all calls to getLoaderManager()
and getFragmentManager()
to getSupportLoaderManager()
and getSupportFragmentManager()
respectively.
Why fragments, and when to use fragments instead of activities?
#1 & #2 what are the purposes of using a fragment & what are the
advantages and disadvantages of using fragments compared to using
activities/views/layouts?
Fragments are Android's solution to creating reusable user interfaces. You can achieve some of the same things using activities and layouts (for example by using includes). However; fragments are wired in to the Android API, from HoneyComb, and up. Let me elaborate;
The
ActionBar
. If you want tabs up there to navigate your app, you quickly see thatActionBar.TabListener
interface gives you aFragmentTransaction
as an input argument to theonTabSelected
method. You could probably ignore this, and do something else and clever, but you'd be working against the API, not with it.The
FragmentManager
handles «back» for you in a very clever way. Back does not mean back to the last activity, like for regular activities. It means back to the previous fragment state.You can use the cool
ViewPager
with aFragmentPagerAdapter
to create swipe interfaces. TheFragmentPagerAdapter
code is much cleaner than a regular adapter, and it controls instantiations of the individual fragments.Your life will be a lot easier if you use Fragments when you try to create applications for both phones and tablets. Since the fragments are so tied in with the Honeycomb+ APIs, you will want to use them on phones as well to reuse code. That's where the compatibility library comes in handy.
You even could and should use fragments for apps meant for phones only. If you have portability in mind. I use
ActionBarSherlock
and the compatibility libraries to create "ICS looking" apps, that look the same all the way back to version 1.6. You get the latest features like theActionBar
, with tabs, overflow, split action bar, viewpager etc.
Bonus 2
The best way to communicate between fragments are intents. When you press something in a Fragment you would typically call StartActivity()
with data on it. The intent is passed on to all fragments of the activity you launch.
What is the difference between Fragment and FragmentActivity?
A Fragment
is a section of an Activity
, which has:
- its own lifecycle
- receives its own input events
- can be added or removed while the
Activity
is running.
A Fragment
must always be embedded in an Activity
.
Fragments
are not part of the API prior to HoneyComb (3.0). If you want to use Fragments
in an app targeting a platform version prior to HoneyComb, you need to add the Support Package to your project and use the FragmentActivity
to hold your Fragments
. The FragmentActivity
class has an API for dealing with Fragments
, whereas the Activity
class, prior to HoneyComb, doesn't.
If your project is targeting HoneyComb or newer only, you should use Activity
and not FragmentActivity
to hold your Fragments
.
Some details:
Use android.app.Fragment
with Activity
. Use android.support.v4.app.Fragment
with FragmentActivity
. Don't add the support package Fragment
to an Activity
as it will cause an Exception to be thrown.
A thing to be careful with: FragmentManager
and LoaderManager
have separate support versions for FragmentActivity:
If you are using a Fragment
in an Activity
(HoneyComb and up), call
getFragmentManager()
to getandroid.app.FragmentManager
getLoaderManager()
to getandroid.app.LoaderManager
if you are using a Fragment
in a FragmentActivity
(pre-HoneyComb), call:
getSupportFragmentManager()
to getandroid.support.v4.app.FragmentManager
.getSupportLoaderManager()
to getandroid.support.v4.app.LoaderManager
so, don't do
//don't do this
myFragmentActivity.getLoaderManager();
//instead do this:
myFragmentActivity.getSupportLoaderManager();
or
//don't do this:
android.app.FragmentManager fm = myFragmentActivity.getSupportFragmentManager();
//instead do this:
android.support.v4.app.FragmentManager fm = myFragmentActivity.getSupportFragmentManager()
Also useful to know is that while a fragment has to be embedded in an Activity
it doesn't have to be part of the Activity
layout. It can be used as an invisible worker for the activity, with no UI of its own.
Difference in Context for Activity and Fragment?
Activity extends Context, but Fragments do not. This is why you can pass it this
for a context parameter. So the error message sees your ScanFragment as a parameter for Context which does not work. Each Fragment is associated with an Activity's fragment. You can either use getActivity()
or getActivity().getApplicationContext()
to receive a valid context to use in these situations.
Your new code would be:mPreview = new CameraPreview(getActivity(), mCamera, previewCb, autoFocusCB);
What's the core difference between fragment and activity? Which code can be written in fragment?
Of course you can write any code inside the fragment but you need to take care of a few things. While accessing anything that requires a context or something that is specific to an activity you will need to get a reference to the super activity of the fragment, e.g. while creating an intent inside an activity you do something like this :
Intent intent = new Intent(this,SomeActivity.class);
but inside a fragment you will have to do something like this:
Intent intent = new Intent(super.getActivity(),SomeActivity.class);
Similarly if you are accessing some thing from the layout file of the fragment. You need to perform the following steps:
1)get a global reference to the parent layout of your fragment inside your fragment. e.g
private LinearLayout result_view;
2) Implement the OnCreateView method instead of onCreate method.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return result_view;
}
3) Inflate the fragment layout like this inside the onCreateView method of the fragment:
result_view = (LinearLayout) inflater.inflate(
R.layout.image_detail_pager, container, false);
4) you can now access layout views like this :
layout_a = (LinearLayout) result_view
.findViewById(R.id.some_layout_id);
What is the difference between context and activity inside a fragment?
with context > intent exists as long as application exists
with activity > intent exists as long as the activity exists
now you know what you need most of the cases.. :-D
Related Topics
Android Listview with Checkbox and All Clickable
Does Broadcastreceiver.Onreceive Always Run in the UI Thread
Expand/Collapse Lollipop Toolbar Animation (Telegram App)
Autoincrement Versioncode with Gradle Extra Properties
Android - Startactivityforresult Immediately Triggering Onactivityresult
How to Check If Receiver Is Registered in Android
Android How to Create Runtime Thumbnail
Using Disklrucache in Android 4.0 Does Not Provide for Opencache Method
Get the Distance Between Two Geo Points
How to Add Action Bar from Support Library into Preferenceactivity
Android Textview:"Do Not Concatenate Text Displayed with Settext"
Avoid Button Multiple Rapid Clicks
How to Auto-Start an Android Application
Wrong Requestcode in Onactivityresult
Retrieve Google Access Token After Authenticated Using Firebase Authentication
Confusion on Yuv Nv21 Conversion to Rgb
Inflateexception with Floatingactionbutton from Official Design Library