在我的应用中,我使用ContentProvider
并使用LoaderManager.LoaderCallbacks<Cursor>.
片段(查看)
public class ArticleCatalogFragment extends BaseFragment
implements ArticleCatalogPresenter.View,
LoaderManager.LoaderCallbacks<Cursor> {
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return onCreateArticleCatalogLoader(args);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
data.registerContentObserver(new LoaderContentObserver(new Handler(), loader));
updateUI(data);
}
private Loader onCreateArticleCatalogLoader(Bundle args) {
int categoryId = args.getInt(CATEGORY_ID);
Loader loader = new ArticleCatalogLoader(this.getActivity(), categoryId);
return loader;
}
}
从MVP的角度来看,我需要:
演示者
public class ArticleCatalogPresenter extends BasePresenter
implements LoaderManager.LoaderCallbacks<Cursor> {
View view;
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return onCreateArticleCatalogLoader(args);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
data.registerContentObserver(new LoaderContentObserver(new Handler(), loader));
view.updateUI(data);
}
private Loader onCreateArticleCatalogLoader(Bundle args) {
int categoryId = args.getInt(CATEGORY_ID);
Loader loader = new ArticleCatalogLoader(context, categoryId); // need Context
return loader;
}
interface View {
updateUI(Cursor data)
}
}
因此,我需要在Presenter中使用上下文。
有一些细微差别:
了解Android。
我现在担心如何避免出现诸如内存泄漏之类的问题,以及如何最好地在Presenter中传递Context,使用Application Context或Activity/Fragment?
最佳答案
向演示者添加上下文是不好的,因为演示者负责业务逻辑。要处理上下文,您需要具有“片段/ Activity ”
在接口(interface)的帮助下利用回调,该接口(interface)将说明在处理 View 时 Activity /片段需要执行哪些操作。
片段/ Activity 负责提供上下文。
例子:
interface BaseContract {
interface BaseView {
//Methods for View
void onDoSomething();
}
interface BasePresenter {
void doSomething();
}
}
class BaseMainPresenter implements BaseContract.BasePresenter {
BaseContract.BaseView view;
BaseMainPresenter(BaseContract.BaseView view) {
this.view = view;
}
@Override
public void doSomething() {
if (view != null)
view.onDoSomething();
}
}
class DemoClass implements BaseContract.BaseView {
//Create object of Presenter
/****
* Example :
* BaseMainPresenter baseMainPresenter = new BaseMainPresenter(this);
*/
@Override
public void onDoSomething() {
//Deal with Context here.
}
}
关于android - Android MVP : safe use Context in Presenter,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31951537/