2

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

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

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

这是代码:

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);
}
4

1 回答 1

4

您必须像这样调用片段:

    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;
    }
}
于 2013-07-02T09:37:54.417 回答