Android Fragment avoid non-default constructors in fragments use a default constructor plus fragment

一、出现情况。

新建Fragment并自定义构造函数传递参数的时候。

二、出现原因。

当Fragment被销毁,在重建的时候,系统只会调用默认的无参构造函数,这样我们自己定义的参数就有可能不能正确初始化,所以会提示上述错误。


三、解决办法。

1.把参数以Bundle的方式与Fragment进行绑定。如下:

Bundle args = new Bundle();
args.putLong("key", value);
yourFragment.setArguments(args);
然后:

Type value = getArguments().getType("key");

2.构造静态工厂方法(推荐)

public class MyFragment extends Fragment {

    /**
     * Static factory method that takes an int parameter,
     * initializes the fragment's arguments, and returns the
     * new fragment to the client.
     */
    public static MyFragment newInstance(int index) {
        MyFragment f = new MyFragment();
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);
        return f;
    }

}
这样做可以使代码更加简洁易懂,并可以防止忘记初始化参数的情况。


参考:

http://stackoverflow.com/questions/12062946/why-do-i-want-to-avoid-non-default-constructors-in-fragments
http://www.androiddesignpatterns.com/2012/05/using-newinstance-to-instantiate.html


第二篇文章最近的一条评论值得一看,讲的就是为什么用setArguments(args)的方式进行传参:

I see this all the time, so maybe you should mention that it's never a good idea to create a Fragment with additional constructors. You do it correctly in the article by using setArguments(Bundle), but it's not clear for new developers what to do if they need to pass arguments to their Fragment, and they may wonder why you use the cumbersome setArguments(Bundle). The answer is that Android only recreates Fragments it kills using the default constructor, so any initialization you do in additional constructors will be lost. Not sure if it's out of the scope of your article or not.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值