【发布时间】:2016-02-15 09:55:51
【问题描述】:
我正在构建一个应用程序,它将支持here 提到的多种设备尺寸。
要处理 inside Fragment 的视图,可以在 Activity 的 onCreate() 或 Fragment 的 onViewCreated() 中使用 findViewById 进行查找。
它们都可以工作,因为:如果您从 Activity 执行此操作,您将处理 Fragment 父级,并且您的 View 仍将在其中,如果您从 Fragment 执行此操作,它将有正常的findViewById 行为。
所以……
- 进行视图查找的最佳位置是什么?
- 哪个更快?
- 哪个效率更高?
两者各有优势:
如果您在Activity 中进行操作:
- 您可以直接在托管 Activity 中控制用户交互(如点击监听器)。
- 您不需要实现从 Activity 到 Fragment 的接口回调。
如果您在Fragment 中进行操作:
- 视图在它们使用的上下文中被实例化。
- 片段可以在同一布局中重复使用。
顺便还有this question。他们在其中讨论了使用 getView 或 getActivity 在Fragment 中调用findViewById。
接受的答案是:
而不是使用 getActivity().findViewById(),你会想要 getView().findViewById()。这样做的原因是,如果您使用 视图查找的活动,那么你会遇到麻烦 多个具有相同视图 ID 的片段附加到它
但是,如果您永远不会在同一布局中重复使用 Fragment,那会是在 Activity 中进行查找的好案例吗?
示例布局:
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>
您可以从Activity 或Fragment 访问带有id a_main_recycler 的RecyclerView。
【问题讨论】:
-
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().错误!要在片段中查找视图,您应该在片段中进行!
标签: android android-layout android-fragments android-activity