The best way to use context in a fragment

im using fragments in my application. I created one parent class called BaseFragment, and the whole other fragment extends this Basefrgment below - this is a fragment of this Basefragment

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

and in all other fragments of i, using activity as a context, my question is whether this is a bad way to access the context in this way or whether it creates a memory leak. Or any other approach to accessing the context. Any help is approximated.

+4
source share
5 answers

, context , . MainActivity - , , . Activity-Fragment, , , . , . :

public MainActivity activity;

. - context = fragIns.activity . , . , , , - . " ".

, , . :

protected MainActivity activity;

.

+1

- getActivity() , , .

+1

getActivity() - , , .

, , , imo, .

@Override
public void onAttach(Activity activity) {        
    super.onAttach(activity);
    mContext=activity;
}
+1

:

public class AppManager extends Application {


    private static AppManager mApp;

    @Override
    public void onCreate() {
        super.onCreate();
        mApp = this;
    }

    public static Context getContext() {
        return mApp.getApplicationContext();
    }
}

Context, AppManager.getContext(), Activity. .

-, , . Activty, , Activity , , , OnAttch(), NullPointerException.

:

public abstract class BaseTabActivity extends BaseActivity {

    @CallSuper
    protected void initTabs(boolean isRestarted) {
        if (isRestarted) {
            FragmentManager manager = getSupportFragmentManager();
            FragmentTransaction transaction = manager.beginTransaction();
            if (manager.getFragments() == null)
                return;
            Stream.of(manager.getFragments())
                    .forEach((fragment) -> {
                        if (fragment != null)
                            transaction.remove(fragment);
                    });
            transaction.commit();
            manager.executePendingTransactions();
        }
    }

    public FragmentTransaction getSlideAnimTransaction() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.setCustomAnimations(R.anim.slide_from_right, R.anim.slide_out_left);
        return transaction;
    }

}
0

To avoid memory problems, it is recommended that whenever you use onAttach(Context context), you should use onDetach():

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (activity == null && context instanceof  MainActivity) {
        activity = (MainActivity) context;
    }
}

@Override
public void onDetach() {
    this.activity = null;
    super.onDetach();
}
0
source

Source: https://habr.com/ru/post/1650386/


All Articles