android - 如何避免 fragment 中的非默认构造函数?

标签 android eclipse

这个问题在这里已经有了答案:





Why do I want to avoid non-default constructors in fragments?

(6 个回答)


9年前关闭。




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

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



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

这是代码:

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

最佳答案

您必须像这样调用 fragment :

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

关于android - 如何避免 fragment 中的非默认构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17422111/

相关文章:

Android:如何创建 "Ongoing"通知?

c++ - 为什么 "all"附加到我在 Eclipse 中的自定义构建命令?

android - 如何在android中的webview上加载网页?

android - 如何从 Flex Mobile 中的另一个应用程序调用一个应用程序

java - 动态更改 BLE 广告数据 Android

java - 在 Eclipse 中将 3 个项目添加到版本控制 (SVN)

linux - 使用 Eclipse 在 Linux 内核上进行开发

javascript - 查找距离我当前位置最近的 friend

c++ - JDK9 Hotspot debug using gdb, causing SIGSEGV Segmentation fault in eclipse/Ubuntu 终端

eclipse - 为什么我收到意外的 URLConnection defaultUseCaches