-3

I don't want to create new class extends Fragment, I want to create new object of Fragment:

Fragment myFrag = new Fragment();

But how to set main view (layout) in my myFrag?

When I extends Fragment via creating new class I do:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.login_fragment, container, false);
}

But in my case how to do it?

Can some one help me?

Magnus2005
  • 97
  • 3
  • 13

1 Answers1

1

You should create new class extends Fragment.

You can use anonymous class, but this is anti-pattern.

    Fragment myFrag = new Fragment() {
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            return inflater.inflate(R.layout.login_fragment, container, false);
        }
    };

AndroidStudio shows a warning.

Fragments should be static such that they can be re-instantiated by the system, and anonymous class are not static

This answer may be useful.
https://stackoverflow.com/a/9245510/5183999

Community
  • 1
  • 1
nshmura
  • 5,940
  • 3
  • 27
  • 46