when i create blank Activity with fragment in android studio what is actually done ! Specifically how they attached together ? in which line of code and how this done ?
3 Answers
What is actually done?
It creates a template out of the following files.
- One
Activity
with a layout - One
ActivityFragment
with a layout - One
strings.xml
value for the title of the Activity - One
res/menu
resource for the Toolbar menu - Adds an
<activity>
section to theAndroidManifest.xml
How are they attached together? In which line of code?
In the onCreate
for the Activity, you set the layout
setContentView(R.layout.activity_main);
Which attaches the Fragment with a <fragment>
tag like this, which is basically a FrameLayout
.
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/fragment"
android:name="com.androidstack.app.MainActivityFragment"
tools:layout="@layout/fragment_main"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

- 179,855
- 19
- 132
- 245
Please read about it here. Google's docs should help you understand a bit.
However a short version is this:
in the Activity's onCreate
:
- Activity's view is drawn.
- Fragment is instantiated.
in the fragments's onAttach
:
- Fragment is attached to Activity
in the fragment's onCreate
:
- fragment is created
in the Fragment's onViewCreated
:
- Fragment's view is drawn.

- 5,379
- 2
- 28
- 47
-
thanks for explanation and now i reading Google's docs for more understanding – Mohamed Yehia Mar 14 '16 at 21:51
Just think of it as an activity within an activity. It is essentially the same things as changing the activity
by using an intent
but is just within it. So there is a parent activity
, within it is the frame
or layout
that holds the fragment. When the parent activity
is done loading it will begin to load the contents of the layout
's, which is your fragment. Contents of that fragment
can be accessed by using v.OnclickListener
and so on

- 1,905
- 2
- 21
- 50
-
i was trying to find in which line they attached and i found it so really thank you for your help – Mohamed Yehia Mar 14 '16 at 21:54
-