Call parent's activity from a fragment

前端 未结 3 690
别那么骄傲
别那么骄傲 2020-12-15 16:19

If I\'m inside a Fragment how can I call a parent\'s activity?

3条回答
  •  猫巷女王i
    2020-12-15 16:37

    The most proper way is to make your Activity implement an Interface and use listeners. That way the Fragment isn't tied to any specific Activity keeping it reusable. Into the Fragment:

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    
        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }
    

    That way, you make the Activity listen to the fragment when it's attached to it.

    See also:

    • http://developer.android.com/training/basics/fragments/communicating.html

提交回复
热议问题