Avoid non-default constructors in fragments: use a default constructor plus setArguments()错误提示解决方法

在创建fragment时,你可能在打包时碰到如下错误

Error: Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead [ValidFragment]   或者   Every fragment must have an empty constructor, so it can be instantiated when restoring its activity's state. It is strongly recommended that subclasses do not have other constructors with parameters, since these constructors will not be called when the fragment is re-instantiated; instead, arguments can be supplied by the caller with setArguments(Bundle) and later retrieved by the Fragment with getArguments().

其原因是你重载了fragment的构造方法,但是在一些情况下,如屏幕翻转时,fragment被重新创建,就可能会造成数据丢失。

转载:http://blog.csdn.net/chniccs/article/details/51258972

解决方案一(不推荐):@SuppressLint({"NewApi", "ValidFragment"})

在构造方法上加上这个注解,就可以不检察,但是这是google不推荐的做法

解决方案二(也不推荐):不报错

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. lintOptions {  
  2.     abortOnError false  
  3. }  
这段加到项目的gradle文件中就可以不报这个错误了,不过这只是让他不报而已,实际上还是存在问题的,所以也不推荐这样做。

解决方案三(推荐):创建newInstance方法来

这种方式避免了使用构造来传参数

创建newInstance方法

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. public static final SplashViewPagerFragment newInstance(int pid, String message)  
  2. {  
  3.     SplashViewPagerFragment fragment = new SplashViewPagerFragment();  
  4.     Bundle bundle = new Bundle();  
  5.     bundle.putInt("pid",pid);  
  6.     bundle.putString("message", message);  
  7.     fragment.setArguments(bundle);  
  8.   
  9.     return fragment ;  
  10. }  

重写onCreate

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @Override  
  2.     public void onCreate(@Nullable Bundle savedInstanceState) {  
  3.         super.onCreate(savedInstanceState);  
  4.           
  5.         mMessage=savedInstanceState.getString("message");  
  6.         mPid=savedInstanceState.getInt("pid");  
  7.   
  8.           
  9.     }  

创建fragment实例

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. SplashViewPagerFragment splashViewPagerFragment=SplashViewPagerFragment.newInstance(1,"测试");  

通过上面的这种方式就可以解决问题。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值