Programing

활동에서 현재 활성화 된 모든 조각에 대한 참조를 얻는 방법이 있습니까?

lottogame 2020. 12. 4. 07:43
반응형

활동에서 현재 활성화 된 모든 조각에 대한 참조를 얻는 방법이 있습니까?


활동에서 현재 활성화 된 (표시, 현재 재개 된 상태) 조각을 모두 가져 오는 간단한 방법을 찾지 못했습니다. 내 활동에서 사용자 정의 부기없이 가능합니까? FragmentManager가이 기능을 지원하지 않는 것 같습니다.


API가 현재 "getFragments"와 같은 메소드를 놓친 것 같습니다.
그러나 Activity 클래스의 "onAttachFragment"이벤트를 사용하면 원하는 작업을 매우 쉽게 수행 할 수 있습니다. 나는 다음과 같이 할 것입니다.

List<WeakReference<Fragment>> fragList = new ArrayList<WeakReference<Fragment>>();
@Override
public void onAttachFragment (Fragment fragment) {
    fragList.add(new WeakReference(fragment));
}

public List<Fragment> getActiveFragments() {
    ArrayList<Fragment> ret = new ArrayList<Fragment>();
    for(WeakReference<Fragment> ref : fragList) {
        Fragment f = ref.get();
        if(f != null) {
            if(f.isVisible()) {
                ret.add(f);
            }
        }
    }
    return ret;
}

객체에서 상태를 읽을 준비가 된 메서드 (예제에서는 isActive ())가없는 경우 onResume 및 onPause를 재정 의하여 플래그를 설정합니다 (단순한 부울 필드 일 수 있음).
그것은 이미 자신의 부기이지만 달성하려는 매우 구체적인 목표를 고려할 때 내 의견으로는 여전히 매우 제한적입니다 (상태 의존 목록).


Android 지원 라이브러리를 사용하는 경우 숨겨진 FragmentManager.getFragments()메서드를 호출 할 수 있습니다 .

public List<Fragment> getVisibleFragments() {
    List<Fragment> allFragments = getSupportFragmentManager().getFragments();
    if (allFragments == null || allFragments.isEmpty()) {
        return Collections.emptyList();
    }

    List<Fragment> visibleFragments = new ArrayList<Fragment>();
    for (Fragment fragment : allFragments) {
        if (fragment.isVisible()) {
            visibleFragments.add(fragment);
        }
    }
    return visibleFragments;
}

이를 수행하는 또 다른 방법은 활동에 태그를 추가 할 때 조각에 태그를 배치하는 것입니다.

예를 들어 4 개의 조각을 동적으로 추가하는 경우 다음과 같이 추가 할 수 있습니다.

for (int i = 0; i < NUM_FRAGMENTS; i++){
    MyFragment fragment = new Fragment(i);
    fragmentTransaction.add(R.id.containerId, fragment, SOME_CUSTOM_PREFIX + i).commit()
}

그런 다음 나중에 모든 조각을 다시 가져와야하는 경우 다음을 수행 할 수 있습니다.

for (int i = 0; i < NUM_FRAGMENTS; i++) {
     String tag = SOME_CUSTOM_PREFIX + i;
     fragmentList.add((MyFragment) fragmentManager.findFragmentByTag(tag));
}

나는 이것을 해결했다.

public ArrayList<Fragment> getAllFragments() {
    ArrayList<Fragment> lista = new ArrayList<Fragment>();

    for (Fragment fragment : getSupportFragmentManager().getFragments()) {
        try {
            fragment.getTag();
            lista.add(fragment);
        } catch (NullPointerException e) {

        }
    }

    return lista;

}

android.support.v4.app.FragmentManager has a method called getFragments() which does exactly what you need, but it was never accessible. Suddenly, though, it is, but I'm not sure if that's intended because it's still marked as hidden.

/**
 * Get a list of all fragments that have been added to the fragment manager.
 *
 * @return The list of all fragments or null if none.
 * @hide
 */
public abstract List<Fragment> getFragments();

The regular android.app.FragmentManager doesn't have this method at all, but if really needed, you can access the same object by getting the field mActive via reflection (be careful there: starting with API 26, its type is a SparseArray instead of List). Use at own risk :)


we can use some irregular-but-legal method

    ArrayList<Fragment> getActiveFragments() {
        Fragment f;
        final ArrayList<Fragment> fragments = new ArrayList<>();
        int i = 0;
        try {
            while ((f = getFragmentManager().getFragment(new Intent().putExtra("anyvalue", i++).getExtras(), "anyvalue")) != null) {
                fragments.add(f);
            }
        } catch (IllegalStateException ex) {

        }
        return fragments;
    }

참고URL : https://stackoverflow.com/questions/6102007/is-there-a-way-to-get-references-for-all-currently-active-fragments-in-an-activi

반응형