啊哈哈哈 没验证 好像没错吧
提供一个int INDEX和一个 String key的搜寻方法。
FragmentManager manager;
Fragment fragmentA, fragmentB;
public void show(int showIndex, int fragmentId) {
if (manager == null) {
manager = getSupportFragmentManager();
}
FragmentTransaction transaction = manager.beginTransaction();
hide(showIndex, transaction);
if (showIndex == 0) {
if (fragmentA == null) {
fragmentA = new Fragment();
transaction.add(fragmentId, fragmentA);
}
} else {
if (fragmentB == null) {
fragmentB = new Fragment();
transaction.add(fragmentId, fragmentB);
}
}
transaction.show(fragmentA).commit();
}
/**
*
* @param showIndex
* 0,1
*/
public void hide(int showIndex, FragmentTransaction transaction) {
if (showIndex == 0) {
if (fragmentA != null) {
transaction.hide(fragmentA);
}
} else {
if (fragmentB != null) {
transaction.hide(fragmentB);
}
}
}
/**
*
* @param key
* @param fragmentId
*/
public void showB(String key, int fragmentId) {
if (manager == null) {
manager = getSupportFragmentManager();
}
FragmentTransaction transaction = manager.beginTransaction();
hideB(key, transaction);
Fragment f = manager.findFragmentByTag(key);
if (f == null) {
if (key.equals("A")) {
fragmentA = new Fragment();
transaction.add(fragmentId, fragmentA, key);
f = fragmentA;
}
if (key.equals("B")) {
fragmentB = new Fragment();
transaction.add(fragmentId, fragmentB, key);
f = fragmentB;
}
}
transaction.show(f).commit();
}
/**
* 显示的KEY,其他的需要隐藏
*
* @param showKey
* @param transaction
*/
public void hideB(String showKey, FragmentTransaction transaction) {
if (showKey.equals("B")) {
if (fragmentA != null) {
transaction.hide(fragmentA);
}
} else {
if (fragmentB != null) {
transaction.hide(fragmentB);
}
}
}