Unable to instantiate Fragment

后端 未结 12 2124
无人及你
无人及你 2020-12-24 06:42

Unable to instantiate fragment make sure class name exists, is public, and has an empty constructor that is public

Is it because my Fr

12条回答
  •  梦毁少年i
    2020-12-24 07:27

    Your Fragment shouldn't have constructors (see this documentation and its examples).

    You should have a newInstance() static method defined and pass any parameters via arguments (bundle)

    For example:

    public static final MyFragment newInstance(int title, String message)
    {
        MyFragment fragment = new MyFragment();
        Bundle bundle = new Bundle(2);
        bundle.putInt(EXTRA_TITLE, title);
        bundle.putString(EXTRA_MESSAGE, message);
        fragment.setArguments(bundle);
        return fragment ;
    }
    

    And read these arguments at onCreate:

    @Override
    public Dialog onCreate(Bundle savedInstanceState)
    {
        title = getArguments().getInt(EXTRA_TITLE);
        message = getArguments().getString(EXTRA_MESSAGE);
    
        //...
        //etc
        //...
    }
    

    This way if detached and re-attached the object state can be stored through the arguments, much like bundles attached to Intents.

提交回复
热议问题