MVP:管理 Activity 和 Fragments 的最佳实践
MVP: Best practice to manage Activities and Fragments
我有一个 Activity
和两个 Fragments
。我决定为每个 "view" 配备一名主持人。因此,主 Activity 有 1 个演示者,第一个片段有 1 个演示者,第二个片段有 1 个演示者。
我有一些用例,但我不知道哪个代码去哪里了。
首先是片段管理器在哪里管理片段?我是否必须在 activity 或他的主持人中像 "beginTransaction().add" 这样的电话?
第二个是,当用户点击 activity 中的按钮时,我必须在当前片段中做一些事情。我是否必须调用 activity 的演示者来调用所需的片段方法,或者直接在 activity 中的 onClick 方法中调用此片段的方法?
PS: 我不想使用任何 lib/framework
The first is where to manage fragments with fragment manager ? Do I
have to do calls like "beginTransaction().add" in the activity or in
his presenter ?
所有与 Android API 相关的内容都应该在 Activity
中。所以,beginTransaction()
是 FragmentManager
的一个方法,这是 Android API 的一部分。 Activity
是您的应用程序与操作系统之间的契约。演示者甚至不知道它用于 Android 应用程序。例如,如果您按下 Activity
内的按钮,它会变成这样:
你的 Activity 内部事件处理程序方法你这样做:
调用 activityPresenter.onButtonClicked()
它将调用 activityView.presentWhatTheButtonClickDid()
The second is, when the user tap on a button in the activity, I've to
do some things in the current fragment. Do I have to call the
presenter of the activity which will call the fragment's method
wanted, or directly in the method onClick in the activity I call this
fragment's method?
您将通过其呈现器间接调用 Fragment 方法。
您的 Activity 内部事件处理程序方法:
调用 activityPresenter.onButtonClicked()
它会调用
fragmentPresenter.onButtonClicked()
它会调用
fragmentView.presentResult()
因此,如您所见,Activitiy 的演示者需要知道 Fragment 的演示者。
*您不应在演示者的名字中使用 "activity" 或 "fragment" 以保持抽象。我这样做只是为了简单。
我有一个 Activity
和两个 Fragments
。我决定为每个 "view" 配备一名主持人。因此,主 Activity 有 1 个演示者,第一个片段有 1 个演示者,第二个片段有 1 个演示者。
我有一些用例,但我不知道哪个代码去哪里了。
首先是片段管理器在哪里管理片段?我是否必须在 activity 或他的主持人中像 "beginTransaction().add" 这样的电话?
第二个是,当用户点击 activity 中的按钮时,我必须在当前片段中做一些事情。我是否必须调用 activity 的演示者来调用所需的片段方法,或者直接在 activity 中的 onClick 方法中调用此片段的方法?
PS: 我不想使用任何 lib/framework
The first is where to manage fragments with fragment manager ? Do I have to do calls like "beginTransaction().add" in the activity or in his presenter ?
所有与 Android API 相关的内容都应该在 Activity
中。所以,beginTransaction()
是 FragmentManager
的一个方法,这是 Android API 的一部分。 Activity
是您的应用程序与操作系统之间的契约。演示者甚至不知道它用于 Android 应用程序。例如,如果您按下 Activity
内的按钮,它会变成这样:
你的 Activity 内部事件处理程序方法你这样做:
调用 activityPresenter.onButtonClicked()
它将调用 activityView.presentWhatTheButtonClickDid()
The second is, when the user tap on a button in the activity, I've to do some things in the current fragment. Do I have to call the presenter of the activity which will call the fragment's method wanted, or directly in the method onClick in the activity I call this fragment's method?
您将通过其呈现器间接调用 Fragment 方法。
您的 Activity 内部事件处理程序方法:
调用 activityPresenter.onButtonClicked()
它会调用
fragmentPresenter.onButtonClicked()
它会调用
fragmentView.presentResult()
因此,如您所见,Activitiy 的演示者需要知道 Fragment 的演示者。
*您不应在演示者的名字中使用 "activity" 或 "fragment" 以保持抽象。我这样做只是为了简单。