关于片段创建

About Fragment Creation

我想知道为什么它需要 putInt 打包。当我滑动到其他选项卡时,是重新创建了我的片段还是使用了上次创建的片段?为什么这里使用了空白构造函数?

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0 : return fragment_zg.newInstance(position + 1);
            case 1: return fragment_Uni.newInstance(position+1);
            default: return fragment_zg.newInstance(position + 1);
    }
}

这是我的 Fragment

public  class fragment_Uni extends Fragment {
    private static final String ARG_SECTION_NUMBER = "section_number";
    public fragment_Uni() {}

    public static fragment_Uni newInstance(int sectionNumber) {
        fragment_Uni uni_fragment = new fragment_Uni();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        uni_fragment.setArguments(args);
        return uni_fragment;
    }
}

那是因为碎片在Android系统中重新创建的方式。当 Android 重新创建片段时,它使用反射(Java 反射 API)重建它们,因此它假定构造函数没有参数(因为其他方式它不知道如何用它)。那么为什么需要片段参数呢?参数存储在 Bundle 对象中,Android 知道如何重新创建,所以这就是它使用 Bundle 的原因,Android 只需将参数 bundle 再次传递给您的片段,您的片段使用存储的重塑自我的价值观。

A Fragment 始终需要默认构造函数,但不能有任何其他构造函数。这就是我们使用静态方法创建实例并将参数传递给它的原因。

这背后的原因是为了保留实例并轻松将数据保存为一个包。

有关详细说明,请参阅 this question

编辑: 为了回答您的其他问题,在这种情况下,每次滑动时都会创建一个新的 Fragment。如果您想保留片段,您应该将 Fragment 设为单例。

I want to know why it needs to putInt into bundle.

如果您想将一些值传递给 Fragment,那么您需要使用 Bundle,然后将其设置为 Fragment 的参数。否则,参数不会在 Fragment 重新创建时保留。如果您的 Fragment 不需要参数或者它不是强制性的,那么 Bundle 可以省略。

When i swipe to other tabs, my fragment is recreated or used last created?

它会使用最后创建的,但是如果你想更新那么你必须刷新你的页面适配器,否则数据不会更新。

Why did blank constructor has been used in this?

它是 Fragment 所需的默认构造函数。