zoukankan      html  css  js  c++  java
  • fragment和自己的activity通讯

    在用到fragment的时候,老是会遇到一个问题,就是fragment与activity之间的通信。下面就来记录一下 activity和fragment之间 通过实现接口来互相通信的方法。
    1. activity 向fragment发出通信,就这么写:


    private OnMainListener mainListener;        // 绑定接口       

    @Override       

    public void onAttachFragment(Fragment fragment) {       

          try {        mainListener = (OnMainListener) fragment;        } catch (Exception e) {        throw new ClassCastException(this.toString() + " must implement OnMainListener");        }       

    super.onAttachFragment(fragment);        }        // 接口       

    public interface OnMainListener {        public void onMainAction();        }

    1. onMainAction 方法是activity向 fragment发出通信的方法,里面可以放参数, 在要发出通信的地方直接调用该方法即可。
    复制代码
    1. 在对应的fragment里面要这么写:
    复制代码

        public class MyFragment extends Fragment implements OnMainListener { 
          public void onMainAction() { 
             //这里是实现通信的接口 


    2. fragment向activity 发出通信:(和前面差不多)

    1.         private OnFragmentListener mListener;
       @Override        public void onAttach(Activity activity) {       

                            super.onAttach(activity);      
               try {        mListener = (OnFragmentListener) activity;       
      } catch (ClassCastException e) {       
      throw new ClassCastException(activity.toString() + " must implement OnFragmentListener");       
      }     
        }      

      public interface OnFragmentListener {        public void onFragmentAction(int flag);        }
     

    在activity中 实现接口:   public   class  MainActivity  extends  Activity  implements  OnFragmentListener{ 

    ………………

    public void onFragmentAction(int flag) { 
    两者都是通过接口的实现来进行通信的,重要的地方就是分别在onAttachFragment 和 onAttach方法中进行接口绑定。 通信还有其他方法的,比如广播、静态handler等,这里就不赘述了。
    end~

    http://www.colabug.com/thread-1124396-1-1.html

    http://blog.csdn.net/t12x3456/article/details/8119607

  • 相关阅读:
    Python学习札记(十五) 高级特性1 切片
    LeetCode Longest Substring Without Repeating Characters
    Python学习札记(十四) Function4 递归函数 & Hanoi Tower
    single number和变体
    tusen 刷题
    实验室网站
    leetcode 76. Minimum Window Substring
    leetcode 4. Median of Two Sorted Arrays
    leetcode 200. Number of Islands 、694 Number of Distinct Islands 、695. Max Area of Island 、130. Surrounded Regions 、434. Number of Islands II(lintcode) 并查集 、178. Graph Valid Tree(lintcode)
    刷题注意事项
  • 原文地址:https://www.cnblogs.com/yc3120/p/4374362.html
Copyright © 2011-2022 走看看