发布于 2017-01-04 03:15:58 | 281 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的精品教程,程序狗速度看过来!

Android移动端操作系统

Android是一种基于Linux的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由Google公司和开放手机联盟领导及开发。尚未有统一中文名称,中国大陆地区较多人使用“安卓”或“安致”。


这篇文章主要介绍了Android 两个Fragment之间传递数据实例详解的相关资料,这里附有实例代码,实现该功能,需要的朋友可以参考下

 Android 两个Fragment之间如何传递数据

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)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务