Using LocalBroadcastManager to communicate from Fragment to Activity

前端 未结 2 1907
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 23:05

EDIT: This question was created as part of one of my first Android projects when I was just starting out with Android application development. I\'m keeping this for historic

2条回答
  •  情书的邮戳
    2020-12-01 23:57

    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

提交回复
热议问题