Android:Fragments should be static such that they can be re-instantiated by the system

  • 问题:Fragments should be static such that they can be re-instantiated by the system, and anonymous classes are not static
    Fragment null must be a public static class to be properly recreated from instance state.

  • Fragment开启事务时用到replace(), 如果使用匿名对象并覆写其onCreateView()方法是会提示错误,给出下面的解决方案:

public class MyFragment extends Fragment {

    private static BasePage basePage;

    public MyFragment(){

    }

    public static final MyFragment newInstance(BasePage page) {
        MyFragment fragment = new MyFragment();
        Bundle bundle = new Bundle();
         basePage = page;
        fragment.setArguments(bundle);
        return fragment ;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if (basePage != null){
            return basePage.rootView;
        }
        return null;
    }
}

猜你喜欢

转载自blog.csdn.net/cnkeysky/article/details/80032241