Android——UI篇:关于Fragment的构造参数打包release版本报错的问题

最近在做项目的途中遇到了问题,本来想着在fragment中创建一个构造参数来传递数据,获取Activity中的数据,如下:

public class FaultVideoFragment extends android.app.Fragment {


    private FaultEnclosureModel model2;
    private FaultDetailsActivity faultDetailsActivity;
    private FaultEnclosureBean faultEnclosureBean;
    private RepairDetailActivity repairDetailActivity;
//    public static String bizId;

    @BindView(R.id.gridView)
    GridView gridView;

    @BindView(R.id.rl_isShow)
    RelativeLayout rlIsShow;

    private View view;

    private int tag = 0;

    public FaultVideoFragment(int tag){
        this.tag = tag;
    }


这种写法debug测试的时候没有问题的,但是在打包release版本时出现如下错误

D:\HZZX\sw023_meis\code\android\Meiz\app\src\main\java\com\hzzx\meiz\fragment\fault\FaultPhotoFragment.java
Error:Error: This fragment should provide a default constructor (a public constructor with no arguments) (com.hzzx.meiz.fragment.fault.FaultPhotoFragment) [ValidFragment]

错误说要使用默认构造函数外加setArguments(Bundle)来代替,去 Android 的官网上查看Fragment的例子都是下面这个样子的:

CharSequence mLabel;  
  
    /** 
     * Create a new instance of MyFragment that will be initialized 
     * with the given arguments. 
     */  
    static MyFragment newInstance(CharSequence label) {  
        MyFragment f = new MyFragment();  
        Bundle b = new Bundle();  
        b.putCharSequence("label", label);  
        f.setArguments(b);  
        return f;  
    }  


好吧,到此为止,暂时没有其他的解决办法,我们只能模仿官网代码来修改我们的代码了,

去掉带参的构造方法,写一个newInstance静态方法,参数为我们需要传递的数据:

public class FaultVideoFragment extends android.app.Fragment {


    private FaultEnclosureModel model2;
    private FaultDetailsActivity faultDetailsActivity;
    private FaultEnclosureBean faultEnclosureBean;
    private RepairDetailActivity repairDetailActivity;
//    public static String bizId;

    @BindView(R.id.gridView)
    GridView gridView;

    @BindView(R.id.rl_isShow)
    RelativeLayout rlIsShow;

    private View view;

    private int tag = 0;



    public static FaultVideoFragment newInstance(int tag) {
        FaultVideoFragment newFragment = new FaultVideoFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("tag", tag);
        newFragment.setArguments(bundle);
        return newFragment;
    }

然后再fragment的OnCreate方法中这样获取:

   @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        Bundle args = getArguments();
        if (args != null) {
            tag = args.getInt("tag");
        }

       
        super.onCreate(savedInstanceState);
    }

在Activity中我们这样发送数据:

 FaultVideoFragment faultVideoFragment = FaultVideoFragment.newInstance(2);


这样在fragment中的OnCreate方法中就可以获取到我们传递的数据了。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值