我在我的应用程序中使用片段。我创建了一个名为 BaseFragment 的父类,所有其他片段都扩展了此 Basefrgment,下面是此 Basefragment 的片段
基础片段.java
public class BaseFragment extends Fragment {
public MainActivity activity;
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (activity == null && context instanceof MainActivity) {
activity = (MainActivity) context;
}
}
}
public void replaceFragment(Fragment fragment, FragmentDetail last) {
fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
boolean push = true;
if (Validator.isNotNull(last)) {
push = false;
}
/*if(Validator.isNull(last)){
transaction.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right);
}else{
transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left);
}*/
transaction.add(R.id.frame_container, fragment, fragment.getClass().getName());
if (Validator.isNull(last) && preferences.getFragmentStack().size() > 0) {
last = preferences.getFragmentStack().lastElement();
}
if (Validator.isNotNull(last)) {
Fragment f = fragmentManager.findFragmentByTag(last.className);
if (Validator.isNotNull(f)) {
f.onPause();
transaction.remove(f);
}
}
last = new FragmentDetail(fragment.getClass().getName(), getTitle().toString(), preferences.isBack());
if (preferences.isBack() || preferences.getFragmentStack().size() == 0) {
if (push) {
preferences.getFragmentStack().push(last);
}
} else {
while (preferences.getFragmentStack().size() > 1) {
preferences.getFragmentStack().pop();
}
if (!preferences.getFragmentStack().lastElement().className.equals(last.className)) {
preferences.getFragmentStack().push(last);
}
}
transaction.commitAllowingStateLoss();
changeNavigationIcon();
// HWUtil.showToast(this,fragmentManager.getBackStackEntryCount() + "");
}
在所有其他片段中,我使用活动作为上下文,我的问题是,以这种方式访问上下文是否是不好的方法,或者它是否会造成内存泄漏。或任何其他访问上下文的方法。任何帮助都适用。
我认为你存储的方式context
确实是最佳选择,因为您将能够在每个子片段实例中使用它。因为MainActivity
是片段中的实例变量,当片段被销毁时它将被垃圾收集。如果我对 Activity-Fragment 生命周期没有误解,那么当您的 Activity 轮换时,将创建新的片段,而旧的片段实例将被销毁。所以,我们在那里也很好。但是,您需要小心上下文变量声明:
public MainActivity activity;
这使得它可以从任何地方访问。任何类都可以调用类似的东西context = fragIns.activity
并将其保存在那里。这对你来说真的很糟糕,因为现在它保存了对该上下文变量的引用。现在,当不再需要您的片段时,它不会被垃圾收集,因为其他一些类正在保存对其变量之一的引用。你会发现自己身处“内存泄漏之城”。
确保您密切关注该变量,并且它的引用不会传递给其他类。由于它位于超类中,因此您可以将其定义为:
protected MainActivity activity;
这应该可以完成工作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)