android关于fragment的构造函数用法建议

关于fragment在打包时找不到一个类的情况:

报错信息:Error : Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead:

原因:


Because of the nature of fragment and how there managed and shown on your screen it's very recommended not to create a non default constructor and in many cases this would cause problems in run time. In case you should do something like this:

因为原生的fragment的管理和在屏幕上显示,是推荐不要在任何继承fragment类里面,去创建类的构造方法,否则在运行时,会出现问题。

A side note for future readers: if your Fragment subclass doesn't declare any constructors at all, then by default an empty public constructor will implicitly be made for you (this is standard Java behavior‌ ). You do not have to explicitly declare an empty constructor unless you also declared other constructors (e.g. ones with arguments).

如果你的fragment没有声明任何的构造函数,系统会自动帮你创建一个构造器。除非你有声明一个带参的构造函数,才需要声明一个无参的构造函数。


而你应该按照如下的来做:

public static final GridFragment newInstance(String tabId)

{

    GridFragment f = new GridFragment();

    Bundle bdl = new Bundle(2);

    bdl.putString(TAB_ID, tabId);

    f.setArguments(bdl);

    return f;

}

and in onCreate extract the needed data from the bundle:

@Override

public void onCreate(Bundle savedInstanceState) 

{

    String tabId = getArguments().getString(TAB_ID);

    }



解决:

if you like to be out of rules just do next

@SuppressLint("ValidFragment")

public PlaceDialogFragment(Place place, DisplayMetrics dm){

        super();

        this.mPlace = place;

        this.mMetrics = dm;

    }

仅仅是警告,避免使用非默认构造函数,因为Fragment源码中用到反射构造了对象,是无参数的构造函数。可以在ShowSynopsis上面加上@SuppressLint("ValidFragment"),忽略警告。

或者加入这句代码@SuppressLint(“ValidFragment")


  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值