I have a question for Android fragment.

Asked 2 years ago, Updated 2 years ago, 102 views

What is the TAG factor used to replace the fragment?

If it is right to find the above fragment with FindFragmentByTag, can I find the removed fragment as well?

I think it doesn't seem to be a problem if you declare the fragment globally and use it without looking for it in the fragment manager But why are you looking for it in the fragment manager?

Thank you.

android fragment

2022-09-22 20:54

1 Answers

Tag can be specified as an option when adding and replacing fragments. This value, as you mentioned, is used to retrieve fragments through the FragmentManager#findFragmentByTag() function.

As you can see from the source code of FragmentManger.java, the function is searched from the list mActive and mAdded in FragmentManager. If you do addToBackStack() even if you delete it, it is searched because the fragment exists in mActive, but if not, it returns null.

ArrayList<Fragment> mAdded;
ArrayList<Fragment> mActive;

...    

@Override
public Fragment findFragmentByTag(String tag) {
    if (mAdded != null && tag != null) {
        // // First look through added fragments.
        for (int i=mAdded.size()-1; i>=0; i--) {
            Fragment f = mAdded.get(i);
            if (f != null && tag.equals(f.mTag)) {
                return f;
            }
        }
    }
    if (mActive != null && tag != null) {
        // // Now for any known fragment.
        for (int i=mActive.size()-1; i>=0; i--) {
            Fragment f = mActive.get(i);
            if (f != null && tag.equals(f.mTag)) {
                return f;
            }
        }
    }
    return null;
}

The second question is, if you change the content a little bit, I think it will help you find the reason. It's the same reason why you can manage and access activities globally, but you don't. Because the life cycle of the fragment, like the activity, is managed by the Android system, you eventually have to create a class like Fragment Manager to handle it elaborately.


2022-09-22 20:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.