0

If I want to reuse a Fragment inside my ArrayAdapter, is that inefficient?

That is, in my ArrayAdapter, my getView() would look like this:

public View getView(final int position, View convertView, ViewGroup parent) {
        UserFragment userFragment = new UserFragment();
        return userFragment.getView();
}

I ask, because normally in the getView() method, it looks something like this:

public View getView(final int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.user, null);
            ...//do stuff
        }

Is it inefficient to create a Fragment each time the getView() is called?

2 Answers 2

2

First, Fragment has its own life cycle, like Activity's onCreate, onDestory, etc.
So if you do UserFragment userFragment = new UserFragment() in getView(), every time you scroll the ListView, a lot of different Fragment's instances will be created and scroll-out ones will be GC. This costs a lot.

Second, you are not reusing views. Each Fragment's instance has its own view structure, so userFragment.getView() will return a brand new View each time.

Basically, it is not recommended to use Fragment inside ListView. Use convertView is more efficient.

Sign up to request clarification or add additional context in comments.

Comments

1

A Fragment is managed by a FragmentManager (through FragmentTransactions) owned by an Activity. Or you can have Fragments in Fragments.

A ListView manages its own views separately and also is recycling these views so when you scroll you'll get in convertView the view that you should use.

Bottom-line is: fragments reside ONLY in activities or in other fragments, while Views (ListView is a descendant of View) stay in Fragments or in Activities.

So: Is it inefficient to create a Fragment each time the getView() is called?. I see no reason why you should do this. In fact, it would be 1000 times more helpful to make push-ups instead of using Fragments in Views. There is not a single good technical article where somebody discusses these.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.