zoukankan      html  css  js  c++  java
  • 两个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 FragmentB extends Fragment {
        public void onBeitieSelected(LinmoBeitieItem item) {
            // ...
        }
    }

    ==

  • 相关阅读:
    关于阿里云带宽监控指标记录
    mongodb备份还原
    squid3.5缓存代理实践记录
    kafka依赖zookeeper原因解析及应用场景
    Zookeeper+Kafka集群部署(转)
    dubbo框架提供Main方法运行容器的几种方式(转)
    html标签简介(常用)
    数据库中和表并列的其他对象
    外键约束
    数据库中的约束
  • 原文地址:https://www.cnblogs.com/graphics/p/5151547.html
Copyright © 2011-2022 走看看