美文网首页
fragment正确使用

fragment正确使用

作者: 不会弹钢琴de大叔 | 来源:发表于2022-07-02 09:25 被阅读0次

近期由于使用单activity和多fragment的框架结构,但是在多指滑动,多点触控时,在fragment的show,hide方法会出现重复添加的异常,Fragment already added,就是相同的fragment在同一时间添加了多个导致这个异常。
通过自己的整理写了一个公共的fragment加载的方法,有需要的可以用一下。亲测好用。

private Fragment currentShowFragment;

private synchronized void showCustomFragment(Fragment fragment) {
        if (currentShowFragment != null && fragment == currentShowFragment) {
            return;
        }
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        hideAllFragment(transaction);
        Fragment tag = getChildFragmentManager().findFragmentByTag(fragment.getClass().getSimpleName());
        if (!fragment.isAdded() && tag == null) {
            transaction.add(R.id.fragment_base, fragment, fragment.getClass().getSimpleName());
        }
        transaction.show(fragment).addToBackStack(null).commit();
        currentShowFragment = fragment;
    }

private void hideAllFragment(FragmentTransaction transaction) {
        if (transaction != null && aFragment!= null) {
            transaction.hide(aFragment);
        }
        if (transaction != null && bFragment!= null) {
            transaction.hide(bFragment);
        }
        if (transaction != null && cFragment!= null) {
            transaction.hide(cFragment);
        }
        //...
    }

showCustomFragment方法就是调用fragment显示的方法,直接使用即可。
hideAllFragment方法是把其他的fragment进行隐藏hide处理。

相关文章

网友评论

      本文标题:fragment正确使用

      本文链接:https://www.haomeiwen.com/subject/smnhbrtx.html