Android managing fragments from activity elegantly

前端 未结 2 661
慢半拍i
慢半拍i 2020-12-16 03:23

Description of what I\'m trying to accomplish: I have an app that uses a FragmentActivity with a LinearLayout as a container for the fragments. I click dif

2条回答
  •  春和景丽
    2020-12-16 03:49

    A co-worker of mine came up with what I consider an elegant solution to this problem.

    Remember, what we're trying to achieve is a way for fragments to callback to the parent activity without having the activity implement the interface. Also, we need to be able to automatically set the listener again if the activity is destroyed and then recreated.

    Activities have a lifecycle callback called onAttachFragment(Fragment fragment) which is called whenever a fragment is being attached to the activity. So, for instance, when a new fragment is created within the activity, this gets called. It also gets called if an activity that was previously destroyed gets recreated. What you can do is use an interface or an anonymous class to set a listener on the new fragment in onAttachFragment like this:

    @Override
    public void onAttachFragment(Fragment fragment) {
        super.onAttachFragment(fragment);
    
        //Determine which fragment this is by checking its tag 
        if(fragment.getTag().contains(TextFrag.FRAG_TAG)){
            //set a listener on this fragment using an anonymous class or interface
            ((TextFrag)fragment).setListener(new TextFragButtonListener() {
                @Override
                public void onButtonClicked() {
                    count++;
                    counterTV.setText(String.valueOf(count));
                }
            });
        }
    }
    

    Using this technique we are able to avoid the activity having to implement an interface for the callback and thus we avoid any naming conflicts with our callback methods. Also, if the activity is destroyed, once it is recreated the listener will be automatically reset so our callbacks will still work.

    There are probably many other ways to do this and I'd love to here anyone's criticisms of this technique and suggestions for any other techniques.

提交回复
热议问题