解决Fragment重影问题

优化Add添加Fragment,在使用hide、show中解决重影问题

初始化中

private FragmentManager fragmentManager;
private List fragmentList = new ArrayList();
//用于记录当前显示的Fragment
private int currentIndex = 0;
protected void initData() {
	fragmentManager = getSupportFragmentManager();
	//初始化三个Fragment
	//不走任何生命周期方法
	conversationFragment = new ConversationFragment();
	contactFragment = new ContactFragment();
	pluginFragment = new PluginFragment();

	fragmentList.add(conversationFragment);
	fragmentList.add(contactFragment);
	fragmentList.add(pluginFragment);

	Fragment fragment0 = fragmentManager.findFragmentByTag("0");
	if (fragment0 != null) {
		fragmentManager.beginTransaction().remove(fragment0).commit();
	}
	Fragment fragment1 = fragmentManager.findFragmentByTag("1");
	if (fragment1 != null) {
		fragmentManager.beginTransaction().remove(fragment1).commit();
	}
	Fragment fragment2 = fragmentManager.findFragmentByTag("2");
	if (fragment2 != null) {
		fragmentManager.beginTransaction().remove(fragment2).commit();
	}

	//默认让消息Fragment选中
	fragmentManager.beginTransaction().add(R.id.fl_content, conversationFragment, "0").commit();
	currentIndex = 0;
}
点击切换Button时

@Override
public void onClick(View v) {
	int index = 0;
	switch (v.getId()) {
		case R.id.iv_conversation:
			index = 0;
			break;
		case R.id.iv_contact:
			index = 1;
			break;
		case R.id.iv_plugin:
			index = 2;
			break;
	}
	if (index == currentIndex) {
		return;
	}
	BaseFragment baseFragment = fragmentList.get(index);
	FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
	//先判断该Fragment是否已经添加到Activity了,如果没有则添加,如果有,则显示
	if (baseFragment.isAdded()) {
		//则显示
		fragmentTransaction.show(baseFragment);
	} else {
		//添加
		fragmentTransaction.add(R.id.fl_content, baseFragment, index + "");
	}
	//隐藏之前显示的Fragment
	fragmentTransaction.hide(fragmentList.get(currentIndex));
	//提交事务
	fragmentTransaction.commit();
	currentIndex = index;
}


你可能感兴趣的:(解决Fragment重影问题)