正如我在 cmets 中提到的,没有唯一的方法可以实现这一点,但理想情况下,非常具体地针对您的主/详细流问题,让我们分析默认提供的示例:
ItemDetialActivity 处理片段创建和显示、FAB 和菜单操作。请注意,与用户数据无关,只有“系统”句柄。例如,我尝试限制活动对导航的责任,以及您确实无法避免的事情,例如菜单按钮处理。现在,ItemListActivity 似乎违反了这一原则,因为它负责显示列表(Google 示例只会在这些关注点分离之间造成混淆-恕我直言),我将创建一个单独的片段,其中包含 RecyclerView 及其适配器。
现在进入细节。这是一个非常的高级框架,希望你可以使用。检查它,实施它,如果有任何问题,请回来:
public interface BaseView {
LifecycleOwner lifecycleOwner();
/* perform actions that affect a basic screen status, like hide/show progress bars and errors,
animate views, etc. */
}
public class BaseRepo {
// will contain LiveData instances which will postValues()
}
public class FooRepo extends BaseRepo {
/* will contain access to database and networking functions, either by creating instance methods
or enforcing with an interface, it's up to you. */
}
public class BaseModel<P extends BasePresenter> extends ViewModel {
protected final FooRepo fooRepo; // optional, can be on concretes
<T> void subscribe(LiveData<T> liveData, Observer<T> observer) {
liveData.observe(view.lifecycleOwner(), observer);
}
<T> void unsubscribe(LiveData<T> liveData, Observer<T> observer) {
if (liveData != null) {
liveData.removeObserver(observer);
}
}
...
}
public abstract class BasePresenter<M extends BaseModel, V extends BaseView> implements LifecycleObserver {
protected V view;
protected M model;
public void setModel(M model) {
this.model = model;
}
public final void attachView(V view, Lifecycle lifecycle) {
this.view = view;
lifecycle.addObserver(this);
}
public void setPresenter(P presenter) {
this.presenter = presenter;
this.presenter.setModel(this);
}
...
}
public abstract class BaseFragment implements BaseView {
/* generics is highly encouraged here, I've seen examples of both BasePresenter<P>
and BaseView<P> */
protected P presenter;
/* You should bind layers here, or in the concrete class,
either with Dagger, reflection, or some other way */
@Override
public LifecycleOwner lifecycleOwner() {
return this;
}
...
}
现在,您应该为每个具体屏幕创建一个从基础派生的演示者、模型和片段,并在那里执行具体操作。希望对你有帮助。