I'm building an application that is going to support multiple device sizes as mentioned here.
To handle the views inside the Fragment
one might either do the lookup with findViewById in the Activity's onCreate()
or in the Fragment's onViewCreated()
.
They would both work because: if you do it from the Activity
you will be handling the Fragment
parent's and your View
will still be inside it, if you do it from the Fragment
it would have the normal findViewById
behavior.
So...
- What is the best place to do the View lookups?
- Which one is faster?
- Which one is more efficient?
They both have their advantages:
If you do them in the Activity
:
- You can control user interactions (like click listeners) right in the hosting Activity.
- You don't need to implement interface callbacks from the Activity to the Fragment.
If you do them in the Fragment
:
- Views are instantiated right in the Context they are used.
- Fragments can be reused in the same layout.
There is this question by the way. In which they debate about the use of getView or getActivity to call findViewById
in the Fragment
.
The accepted answer says:
Rather than using getActivity().findViewById(), you'll want getView().findViewById(). The reason for this is that if you use the activity for the view lookups, then you'll get into trouble when multiple fragments with the same view IDs are attached to it
But what if you will never reuse the Fragment
in the same layout, would that be a good case to do the lookup in the Activity
?
Example layouts:
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<fragment
android:id="@+id/f_main"
class=".fragments.MainFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="@layout/fragment_main" />
</FrameLayout>
fragment_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.MainFragment">
<android.support.v7.widget.RecyclerView
android:id="@+id/a_main_recycler"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
You can access the RecyclerView
with the id a_main_recycler either from the Activity
or the Fragment
.