gpt4 book ai didi

android - 在 fragment 中使用上下文的最佳方式

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:58:21 25 4
gpt4 key购买 nike

我正在我的应用程序中使用 fragment 。我创建了一个名为 BaseFragment 的父类,所有其他 fragment 都扩展了这个 Basefragment 下面是这个 Basefragment 的 fragment

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() + "");

在我使用 Activity 作为上下文的所有其他 fragment 中,我的问题是以这种方式访问​​上下文是否是一种糟糕的方式,或者它是否会造成内存泄漏。或任何其他访问上下文的方法......任何帮助都适用。

最佳答案

我认为您存储 context 的方式确实是最佳的,因为您将能够在每个子 fragment 实例中使用它。因为 MainActivity 是 fragment 中的一个实例变量,所以当 fragment 被销毁时它将被垃圾回收。如果我没有弄错 Activity-Fragment 生命周期,当您的 Activity 旋转时,将创建新的 fragment ,而旧的 fragment 实例将被销毁。所以,我们在那里也很好。但是,您需要注意上下文变量声明:

public MainActivity activity;

这使得它可以从任何地方访问。任何类都可以调用类似 context = fragIns.activity 的东西并将其保存在那里。这对你来说真的很糟糕,因为现在它持有对该上下文变量的引用。现在,当不再需要您的 fragment 时,它不会被垃圾回收,因为其他某个类持有对其变量之一的引用。您会发现自己身处“内存泄漏小镇”。

确保您妥善保管这个变量,并且它的引用不会传递给其他类。因为它在父类(super class)中,您可以将其定义为:

protected MainActivity activity;

这应该可以完成工作。

关于android - 在 fragment 中使用上下文的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38800839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com