我通常在Activity中使用這個方法,它必須替換Fragments:
/**
* This method is used to load the fragment once an item gets selected
*
* @param fragment This is the chosen fragment you want to select
*/
public void loadFragmentActivityFrameLayout(final Fragment fragment) {
// create a transaction for transition here
final FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
// put the fragment in place
transaction.replace(
R.id.frameLayoutId,
fragment,
fragment.getClass().getSimpleName());
// this is the part that will cause a fragment to be added to back stack,
// this way we can return to it at any time using this tag
if(fragment instanceof Fragment1){
transaction.addToBackStack(Fragmen1.class.getSimpleName());
}else if(fragment instanceof Fragment2){
transaction.addToBackStack(Fragment2.class.getSimpleName());
}else if(fragment instance of Fragment3){
transaction.addToBackStack(Fragment3.class.getSimpleName());
}else if(fragment instanceof Fragment4){
transaction.addToBackStack(Fragment4.class.getSimpleName());
}
transaction.commit();
}
然後你就可以在該活動檢索每個片段的情況下,像這樣:
Fragment1 frag1 =
(Fragment1)getSupportFragmentManager()
.findFragmentByTag(Fragment1.class.getSimpleName());
Fragment2 frag2 =
(Fragment2)getSupportFragmentManager()
.findFragmentByTag(Fragment2.class.getSimpleName());
Fragment3 frag3 =
(Fragment3)getSupportFragmentManager()
.findFragmentByTag(Fragment3.class.getSimpleName());
Fragment4 frag4 =
(Fragment4)getSupportFragmentManager()
.findFragmentByTag(Fragment4.class.getSimpleName());
然後,因爲你有一個適配器,使其在片段公開,讓我們說「 frag1" 不要忘記做‘的MyMethod()’的公共插入適配器:
public CustomAdapter adapter;
終於可以從活動獲取任何適配器方法:
frag1.adapter.MyMethod();
希望我已經清楚。