我试图让代码
here工作.它编译好它会运行.它将加载选项卡1(共3个).但是,当我点击第2或第3个选项卡时,我得到:
java.lang.NoSuchMethodError: android.app.FragmentTransaction.detach
这发生在这里的代码中
public void onTabUnselected(Tab tab,FragmentTransaction ft) { if (mFragment != null) { //ft.detach(mFragment); //requires API Level 13 ft.remove(mFragment); //this does not do the same thing as detach } }
我发现detach只能用于API Level 13.我尝试了remove,但是它显然不会做同样的事情.有没有人有任何想法如何克服这个基于第一个link的代码?
解决方法
看起来替换引用附加和分离的代码中的几个位置加上和删除将允许代码在预处理API级别13环境中正常运行.
public TabListener(Activity activity,String tag,Class<T> clz,Bundle args) { mActivity = activity; mTag = tag; mClass = clz; mArgs = args; // Check to see if we already have a fragment for this tab,probably // from a prevIoUsly saved state. If so,deactivate it,because our // initial state is that a tab isn't shown. mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag); if (mFragment != null) { // && !mFragment.isDetached()) { FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction(); //ft.detach(mFragment); ft.remove(mFragment); ft.commit(); } } public void onTabSelected(Tab tab,FragmentTransaction ft) { //if (mFragment == null) { mFragment = Fragment.instantiate(mActivity,mClass.getName(),mArgs); ft.add(android.R.id.content,mFragment,mTag); //} else { // ft.attach(mFragment); //} } public void onTabUnselected(Tab tab,FragmentTransaction ft) { if (mFragment != null) { //ft.detach(mFragment); //requires API 13 ft.remove(mFragment); //this does not do the same thing as detach } }