fragment中的replace和hide与shou方法的区别

fragment中有两种常用的加载方式:
- replace
- hideshou

之前一直没考虑过这个问题,今天突然想起来了,就顺便进去看下源码

replace

源码中对replace方法的说明是这样的

    /**
     * Replace an existing fragment that was added to a container.  This is
     * essentially the same as calling {@link #remove(Fragment)} for all
     * currently added fragments that were added with the same containerViewId
     * and then {@link #add(int, Fragment, String)} with the same arguments
     * given here.
     * 
     * @param containerViewId Identifier of the container whose fragment(s) are
     * to be replaced.
     * @param fragment The new fragment to place in the container.
     * @param tag Optional tag name for the fragment, to later retrieve the
     * fragment with {@link FragmentManager#findFragmentByTag(String)
     * FragmentManager.findFragmentByTag(String)}.
     * 
     * @return Returns the same FragmentTransaction instance.
     */
    public abstract FragmentTransaction replace(@IdRes int containerViewId, Fragment fragment,
            @Nullable String tag);

其实就是add一个,然后remove一个,替换关系

show和hide

再来看show,显示一个之前隐藏的fragment,这说明他并没有被remove,而是被hide了,那么hide就不用看了,肯定放到堆栈了,要show的时候,直接拿出来就行,不会重新new一个

    /**
     * Shows a previously hidden fragment.  This is only relevant for fragments whose
     * views have been added to a container, as this will cause the view to
     * be shown.
     * 
     * @param fragment The fragment to be shown.
     * 
     * @return Returns the same FragmentTransaction instance.
     */
    public abstract FragmentTransaction show(Fragment fragment);

总结

那么综合来说的话,如果单页数据量较大的话,用show和hide还好一些,毕竟二次加载起来要快很多,但是可能会产生内存不足的情况。replace虽然不用就干掉,但是二次加载会慢一些,然而今天之所以要记录一下,是因为我突然发现replace还提供了一个api

    /**
     * Add this transaction to the back stack.  This means that the transaction
     * will be remembered after it is committed, and will reverse its operation
     * when later popped off the stack.
     *
     * @param name An optional name for this back stack state, or null.
     */
    public abstract FragmentTransaction addToBackStack(@Nullable String name);

加到堆栈,要用的时候直接取出来,那么如果replace加上这个就和show与hide有的一拼了。

这样封装一下fragment切换器效果就好多了

    public void fragmentReplace(int target, Fragment toFragment, boolean backStack) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        String toClassName = toFragment.getClass().getSimpleName();
        if (manager.findFragmentByTag(toClassName) == null) {
            transaction.replace(target, toFragment, toClassName);
            if (backStack) {
                transaction.addToBackStack(toClassName);
            }
            transaction.commit();
        }
    }

如果要放到缓存直接给backStack传true即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值