软件编程
位置:首页>> 软件编程>> Android编程>> Android 两个Fragment之间传递数据实例详解

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

作者:lqh  发布时间:2022-06-23 19:30:09 

标签: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) {
   // ...
 }
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

来源:http://www.cnblogs.com/graphics/p/5151547.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com