操作栏选项卡的 FragmentTransaction .attach 和 .detach [英] FragmentTransaction .attach and .detach for Actionbar tabs

查看:56
本文介绍了操作栏选项卡的 FragmentTransaction .attach 和 .detach的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取代码 这里 工作.它编译得很好.它会运行.它将加载选项卡 1(共 3 个).但是,当我点击第二个或第三个标签时,我得到了这个:

I'm trying to get the code here to work. It compiles fine. It will run. And it will load tab 1 (of 3). However, when I click on the 2nd or 3rd tab, I get this:

java.lang.NoSuchMethodError: android.app.FragmentTransaction.detach

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
    }
}

我发现分离 仅适用于 API 级别 13.我试过 remove,但显然它不会做同样的事情.有没有人根据第一个 链接?

I found that detach is only available to API Level 13. I tried remove, but it doesn't do the same thing, obviously. Does anyone have any ideas about how to overcome this based on the code in the first link?

我想 attach 因为它也在代码中,但在应用程序崩溃之前不会被击中.

I guess the same goes for attach as that's also in the code, but doesn't get hit before the app crashes.

推荐答案

看来,将代码中引用 attach 和 detach 的几个地方替换为 add 和 remove 将允许代码在 API Level 13 之前的版本中正常运行环境.

It appears that replacing the several places in the code that reference attach and detach with add and remove will allow the code to function normally in a pre-API Level 13 environment.

    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
        }
    }

这篇关于操作栏选项卡的 FragmentTransaction .attach 和 .detach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆