为没有MVC的简单应用程序使用上下文的最佳实践



我是编程新手。我有一个简单的应用程序,只有几个活动,我需要在这些活动中使用Context。链接:https://openclassrooms.com/en/courses/4661936-develop-your-first-android-application/4679186-learn-the-model-view-controller-patternMVC中对简单应用程序的回答是,我不需要MVC来处理简单应用程序,我想避免使用它。在我的情况下,获取上下文的最佳实践是什么?我认为static Context会导致内存泄漏。每次需要上下文时,我应该只调用getContext()吗?(我测试过,它有效(。它不适用于this,只能用于getContext()。我想这是因为它在碎片里面。谢谢

为了更好地理解:这是我的一部分:

public class MainApplication extends Application 
{
@Override
public void onCreate()
{
super.onCreate();
FirstManager.createInstance(getApplicationContext());
}
}

我在构造函数的帮助下将此上下文传递给FirstManager。如果我有比只有FirstManager更多的活动/类,那么是再次编写getApplicationContext()更好,还是在类范围中在onCreate:getContext()之后编写类似于:Context context;的内容并将其保存到context中更好?

更新:这是片段(其他片段相似,没有什么特别之处(:

public class List extends Fragment {
...
private FloatingActionButton fab;
private FloatingActionButton fdb;
private RecyclerView recyclerView;
...
@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
fab = ( FloatingActionButton ) view.findViewById(R.id.floatingActionButton);
recyclerView = (RecyclerView) view.findViewById(R.id.RView);
fdb = ( FloatingActionButton ) view.findViewById(R.id.floatingDeleteButton);

fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(getContext(), FloatingButtonActivity.class));
}
});
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getContext(),1);
recyclerView.addItemDecoration(dividerItemDecoration);
}
@Override
public void onResume() {
super.onResume();
final RAdapter radapter = new RAdapter(getContext(),getActivity());
recyclerView.setAdapter(radapter);
fdb.hide();
fdb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
radapter.deleteSelection();
}
});
}
}

在每个Fragment中,您都可以使用getContextgetActivity,并可以随心所欲地使用它们。请记住,两者都是Nullable,如果尚未创建片段的根视图,则都将是null。一些示例代码:

@Override
public void onViewCreated(View view) {
...
Context context = getContext();
if (context != null) {
startActivity(new Intent(context, FloatingButtonActivity.class));
...
recyclerView.setLayoutManager(new LinearLayoutManager(context));
...
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(context);
}
}

每次使用这个局部变量和getContext之间没有性能差异,您只需要消除上下文为null的警告。

由于上下文不会暴露在一个生命周期将超过Fragment或Activity的实体之外(这意味着你不会将上下文提供给Fragment或者Activity被杀死后可能存在的任何类实例(,因此从这段代码中你不会有泄漏。

最新更新