Fragment与Activity之间的相互通信

xgga2062 8年前
   <h2><strong>前言</strong></h2>    <p>自从Android3.0引入Fragment之后,主要是为了支持动态灵活的界面设计和屏幕的适配问题。Fragmenty不能单独存在,必须依赖Activity作为视图展示的一部分,同事它具有自己的生命周期,接收它自己的事件,具有更加灵活的特性,如今Fragment已经被广泛的应用到App开发中,最常见的就是单Activity多Fragment的模式。Fragment依赖于Activity而存在,就不可避免需要与Activity进行交互,在这里就简单的介绍三种常用的交互方式。</p>    <p><strong>一、接口方式</strong></p>    <p>在fragment类中定义一个接口并在Activity中实现它。Fragment在onAttach()回调函数中获取接口的具体实现的对象。后面,fragment就可以调用接口中的方法实现与Activity的通信。</p>    <p>在Android5.0之后废除了onAttach(Activity activity)的方法,转而使用onAttach(Context context),也就是传递的参数发生变化</p>    <pre>  <code class="language-java">public interface showMsgListener{          void showMsg(String str);      }        private showMsgListener msgListener;        @Override      public void onAttach(Activity activity) {          super.onAttach(activity);          try {              if(activity!=null){                  msgListener=(MainActivity)activity;              }          } catch (ClassCastException e) {              throw new ClassCastException(activity.toString()                      + " must implement showMsgListener");          }      }            mButton.setOnClickListener(new View.OnClickListener() {              @Override              public void onClick(View view) {                  msgListener.showMsg("Hello Android!(接口)");              }          });</code></pre>    <p>在Activity中需要实现该接口</p>    <pre>  <code class="language-java">@Override      public void showMsg(String str) {          Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();      }</code></pre>    <p><strong>二、广播</strong></p>    <p>在Activity中注册广播接收器,在Fragment中发送广播</p>    <pre>  <code class="language-java">private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {          @Override          public void onReceive(Context context, Intent intent) {              String action = intent.getAction();              if (action.equals(ACTION_NAME)) {                  String msg = intent.getStringExtra("msg");                  Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();              }            }      };        public void registerBoradcastReceiver() {          IntentFilter myIntentFilter = new IntentFilter();          myIntentFilter.addAction(ACTION_NAME);          registerReceiver(mBroadcastReceiver, myIntentFilter);      }        @Override      protected void onDestroy() {          super.onDestroy();          unregisterReceiver(mBroadcastReceiver);      }</code></pre>    <p><strong>三、Fragment 从Activity获取数据</strong></p>    <p>在Fragment 的getInstance()方法中setArguments()设置参数</p>    <pre>  <code class="language-java">public static Fragment getInstance(String msg){          Bundle bundle = new Bundle();          bundle.putString("msg",msg);          MainFragment fragment=new MainFragment();          fragment.setArguments(bundle);          return fragment;      }</code></pre>    <p>再通过getArguments()方法获取</p>    <pre>  <code class="language-java">public void initDatas() {          Bundle bundle=getArguments();          if(bundle!=null){              String msg=bundle.getString("msg");              Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();          }      }</code></pre>    <p> </p>    <p>来自:http://www.jianshu.com/p/f2452d2c8b21</p>    <p> </p>