两个Fragment之间如何传递数据

时间:2023-01-20 20:14:30

FragmentA启动FragmentB,做一些选择操作后,返回FragmentA,需要把FragmentB里面选择的数据传回来。有什么办法?

Fragment之间不能直接通信,必须通过Activity来完成,具体步骤。

1. 在FragmentA中定义通信接口,通过该接口向Activity发送数据。

public class FragmentA extends Fragment {
    private onButtonPressListener mListener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_linmo_select_beitie, container, false);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mListener.onOKButtonPressed(selectedBeitie);
            }
        });

        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (onButtonPressListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement onOkButtonPressed");
        }
    }

    public interface onButtonPressListener {
        void onOKButtonPressed(LinmoBeitieItem item);
    }
}

 

2. 在Activity中实现该接口,并通过该接口向FragmentB传递数据。

public class MainActivity extends Activity implements FragmentA.onButtonPressListener {
    @Override
    public void onOKButtonPressed(LinmoBeitieItem item) {
        FragmentB fragmentB = (FragmentB)getFragmentManager().findFragmentById(R.id.container);
        fragmentB.onBeitieSelected(item);
    }
}

 

3. FragmentB接收到数据并处理。

public class FragmentB extends Fragment {
    public void onBeitieSelected(LinmoBeitieItem item) {
        // ...
    }
}

==