源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Android 两个Fragment之间传递数据实例详解

  • 时间:2022-09-12 00:53 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Android 两个Fragment之间传递数据实例详解
 [b]Android 两个Fragment之间如何传递数据[/b] 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 FragmentA extends Fragment {
  public void onBeitieSelected(LinmoBeitieItem item) {
    // ...
  }
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部