Activity和Fragment之间相互传值和调用方法

1。Activity—>Fragment

用Bundle传值,

...
        BlankFragment fragment = new BlankFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
...

Fragment onCreate中接受值

...
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
 ...

2。Fragment—>Activity

在Fragment中定义接口

...
  public  interface Fragment2AtyListener{
       void onFragment2Aty(Object object);
    }
    ...

让Activity实现Fragment2AtyListener接口

在Fragment中

...
    /**
     * 当Fragment被加载到activity的时候会被回调
     *
     * 判断宿主Activity是否实现了接口MyListener方法1
     * @param context
     */
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        if(context instanceof Fragment2AtyListener)
        {
            mFragment2AtyListener = (Fragment2AtyListener)context;
        }
        else{
            throw new IllegalArgumentException("Activity must implements Fragment2AtyListener");
        }

    }

    /**
     *判断宿主Activity是否实现了接口MyListener方法2
     */
/*    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mFragment2AtyListener = (Fragment2AtyListener) context;
        }catch (ClassCastException e) {
            throw new ClassCastException(getActivity().getClass().getName()
                    +"Activity must implements Fragment2AtyListener");
        }
    }*/

 /**操作传值 通过接口回调*/
 mFragment2AtyListener.onFragment2Aty("数据来自Fragment");
 ...

Activity和Fragment之间相互传值和调用方法_第1张图片

DEMO下载:http://download.csdn.net/detail/richiezhu/9476815

Fragment之间通过Activity相互传值和调用方法
见:http://blog.csdn.net/richiezhu/article/details/51024772

你可能感兴趣的:(Android)