Created
May 23, 2012 09:25
-
-
Save syxc/2774200 to your computer and use it in GitHub Desktop.
动态加载fragment时需要注意!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ... | |
@Override | |
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { | |
Log.i(TAG, "-- onCreateView(...) --"); | |
mRootView = (View) inflater.inflate(R.layout.fragment_login, container, false); | |
return mRootView; | |
} | |
// 当FragmentActivity动态切换Fragment的时候,上面代码片段中的container设置为null或者其后的参数设置为false, | |
// 否则会报出异常: | |
// java.lang.IllegalStateException: The specified child already has a | |
// parent. You must call removeView() on the child's parent first. | |
// 另外,对fragment进行remove操作前记得进行非空判断 | |
// ... | |
protected void goHome() { | |
FragmentTransaction transaction = getFragmentManager().beginTransaction(); | |
HomeFragment homeFragment = new HomeFragment(); | |
if (null == getFragmentManager().findFragmentByTag("tag_home")) { | |
transaction.add(R.id.fragment_main, homeFragment, "tag_home"); | |
} | |
if (null != getFragmentManager().findFragmentByTag("tag_login")) { | |
transaction.remove(getFragmentManager().findFragmentByTag("tag_login")); | |
} | |
transaction.replace(R.id.fragment_main, homeFragment) | |
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) | |
.commit(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment