eclipse 如何避免片段中的非默认构造函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17422111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 20:49:48  来源:igfitidea点击:

How to avoid non-default constructors in fragments?

androideclipse

提问by Shani Goriwal

I'm currently working on an android app, and it suddenly gave me these errors (it used to work like this, which is the strange part):

我目前正在开发一个 android 应用程序,它突然给了我这些错误(它曾经是这样工作的,这是奇怪的部分):

Avoid non-default constructors in fragments: use a default constructor plus Fragment#setArguments(Bundle) instead

避免片段中的非默认构造函数:使用默认构造函数加上 Fragment#setArguments(Bundle) 代替

and

This fragment should provide a default constructor (a public constructor with no arguments)

这个片段应该提供一个默认构造函数(一个没有参数的公共构造函数)

This is the code:

这是代码:

public DatePickerFragment(ProjectOverviewFragment list){
    this.list = list;
    Calendar cal = Calendar.getInstance();

    date = cal.get(Calendar.DAY_OF_MONTH)+"-"+cal.get(Calendar.MONTH)+"-"+cal.get(Calendar.YEAR);
}

回答by Shani Goriwal

You have to call fragment something like this:

你必须像这样调用片段:

    int id;

    Fragment newFragment = CountingFragment.newInstance(id);
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.simple_fragment, newFragment);
    ft.addToBackStack(null);
    ft.commit();

    public static class CountingFragment extends Fragment {
    int mNum;

    static CountingFragment newInstance(int num) {
        CountingFragment f = new CountingFragment();
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);

        return f;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNum = getArguments() != null ? getArguments().getInt("num") : 1;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment, container, false);
        View tv = v.findViewById(R.id.text);
        ((TextView)tv).setText("Hello. This is fragment example #" + mNum);
             tv.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));
        return v;
    }
}