publicclassHeadlinesFragmentextendsListFragment{OnHeadlineSelectedListenermCallback;// Container Activity must implement this interfacepublicinterfaceOnHeadlineSelectedListener{publicvoidonArticleSelected(intposition);}@OverridepublicvoidonAttach(Activityactivity){super.onAttach(activity);// This makes sure that the container activity has implemented// the callback interface. If not, it throws an exceptiontry{mCallback=(OnHeadlineSelectedListener)activity;}catch(ClassCastExceptione){thrownewClassCastException(activity.toString()+" must implement OnHeadlineSelectedListener");}}...}
publicstaticclassMainActivityextendsActivityimplementsHeadlinesFragment.OnHeadlineSelectedListener{...publicvoidonArticleSelected(intposition){// The user selected the headline of an article from the HeadlinesFragment// Do something here to display that article}}
publicstaticclassMainActivityextendsActivityimplementsHeadlinesFragment.OnHeadlineSelectedListener{...publicvoidonArticleSelected(intposition){// The user selected the headline of an article from the HeadlinesFragment// Do something here to display that articleArticleFragmentarticleFrag=(ArticleFragment)getSupportFragmentManager().findFragmentById(R.id.article_fragment);if(articleFrag!=null){// If article frag is available, we're in two-pane layout...// Call a method in the ArticleFragment to update its contentarticleFrag.updateArticleView(position);}else{// Otherwise, we're in the one-pane layout and must swap frags...// Create fragment and give it an argument for the selected articleArticleFragmentnewFragment=newArticleFragment();Bundleargs=newBundle();args.putInt(ArticleFragment.ARG_POSITION,position);newFragment.setArguments(args);FragmentTransactiontransaction=getSupportFragmentManager().beginTransaction();// Replace whatever is in the fragment_container view with this fragment,// and add the transaction to the back stack so the user can navigate backtransaction.replace(R.id.fragment_container,newFragment);transaction.addToBackStack(null);// Commit the transactiontransaction.commit();}}}