ButtoncatButton=(Button)findViewById(R.id.categorybutton);OnClickListenerlistener=/* create your listener here */;if(catButton!=null){catButton.setOnClickListener(listener);}
@OverridepublicvoidonHeadlineSelected(intindex){mArtIndex=index;if(mIsDualPane){/* display article on the right pane */mArticleFragment.displayArticle(mCurrentCat.getArticle(index));}else{/* start a separate activity */Intentintent=newIntent(this,ArticleActivity.class);intent.putExtra("catIndex",mCatIndex);intent.putExtra("artIndex",index);startActivity(intent);}}
Reuse Fragments in Other Activities [在其他Activities里重用Fragments]
某些时候,我们可以重用一些组件,比如in the News Reader sample, the news article text is presented in the right side pane on large screens, but is a separate activity on smaller screens.
在这种情况下,我们可以重用同一个Fragment在若干个Activities里面而避免duplication.例如,ArticleFragment 被使用在dual-pane的布局里面
显然,这样做的效果可以和声明一个布局文件效果一致,在这样的情况下,布局文件其实是另外一个Activity的组件,我们可以直接重复利用
当设计fragments的时候我们需要记住的是:不要为特定的activity创建一个强耦合的fragment,我们可以使用定义一个接口来和host activity进行交互
For example, the News Reader app’s HeadlinesFragment does precisely that:
1234567891011121314
publicclassHeadlinesFragmentextendsListFragment{...OnHeadlineSelectedListenermHeadlineSelectedListener=null;/* Must be implemented by host activity */publicinterfaceOnHeadlineSelectedListener{publicvoidonHeadlineSelected(intindex);}...publicvoidsetOnHeadlineSelectedListener(OnHeadlineSelectedListenerlistener){mHeadlineSelectedListener=listener;}}
publicclassArticleActivityextendsFragmentActivity{intmCatIndex,mArtIndex;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);mCatIndex=getIntent().getExtras().getInt("catIndex",0);mArtIndex=getIntent().getExtras().getInt("artIndex",0);// If should be in two-pane mode, finish to return to main activity if(getResources().getBoolean(R.bool.has_two_panes)){finish();return;}...}