1. 程式人生 > >Activity和Fragment之間相互傳值和呼叫方法

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"); ...

這裡寫圖片描述