Using LocalBroadcastManager to communicate from Fragment to Activity

杀马特。学长 韩版系。学妹 提交于 2019-11-27 09:23:33

You can use Interface for it so main objective of Fragment re-usability is maintained. You can implement communication between Activity-Fragment OR Fragment-Fragment via using following :

I am asuming that your moto is Fragment to communicate with its Activity and other Fragments. If this is the case please go throught it.

To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity. The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods in order to communicate with the Activity.

Example :

# In fragment

    public class HeadlinesFragment extends ListFragment {

    OnHeadlineSelectedListener mCallback;

    public interface OnHeadlineSelectedListener {        
    public void onArticleSelected(int position);    
    }

   @Override   
   public void onAttach(Activity activity) {        
   super.onAttach(activity);
   mCallback = (OnHeadlineSelectedListener) activity;
   }
   @Override    
   public void onListItemClick(ListView l, View v, int position, long id) {
   mCallback.onArticleSelected(position);    
  }
  }

# In Activity

    public static class MainActivity extends Activity  implements HeadlinesFragment.OnHeadlineSelectedListener{
 public void onArticleSelected(int position) {
  // Do something here
 }
 }

Link: http://developer.android.com/training/basics/fragments/communicating.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!