Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

android - Restoring fragment containing dynamically created views from backstack causes IllegalArgumentException because those views are not found

Within the HomeFragment I'm creating FragmentContainerViews and adding them dynamically, based on an async call, in a container then replacing them with fragment instances. Issue is when I click the GoBack arrow from another destination and return to the HomeFragment, this fragment gets restored from the backstack and causes an error because it can't find the FragmentContainerViews that I created.

I can find a workaround/hack for this but want to know what the proper way of handling this should be.

Some other observations: The HomeFrag itself is being created just once, but the fragments I add dynamically within Home are being created twice when coming back from a screen, once from the backstack (which results in error) and once from the onViewCreated of the Home fragment which creates them the same way as the first time the app was launched. "onSaveInstanceState" doesn't get called either within HomeFrag when it is pushed in the backstack.

Sample Code of HomeFragment:

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        ...
        mViewModel.getContentService().fetchHomeConfiguration(new ResponseCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean showTray) {
                if (showTray) addRankedTray();
        ...
            }
            @Override
            public void onError(Throwable error) {...}
        });

    }

    private void addRankedTray() {
        FragmentContainerView fragmentContainerView = new FragmentContainerView(getContext());
        fragmentContainerView.setId("tkRankedTray".hashCode());
        binding.tkHomeContainer.addView(fragmentContainerView);

        getChildFragmentManager().beginTransaction()
                .setReorderingAllowed(true)
                .replace(fragmentContainerView.getId(), new RankedTrayFragment())
                .commit();

    }
question from:https://stackoverflow.com/questions/65852205/restoring-fragment-containing-dynamically-created-views-from-backstack-causes-il

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...