Fragment保持状态替换,以防止重复加载

啊哈哈哈 没验证 好像没错吧

提供一个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);
			}
		}
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值