Greelings
Greelings

Reputation: 5434

Android : What is the difference between View.inflate and getLayoutInflater().inflate?

What is the real difference between :

return context.getLayoutInflater().inflate(R.layout.my_layout, null);

Inflate a new view hierarchy from the specified xml resource.

and

return View.inflate(context, R.layout.my_layout, null);

Inflate a view from an XML resource. This convenience method wraps the LayoutInflater class, which provides a full range of options for view inflation.

Upvotes: 5

Views: 2442

Answers (2)

Sunny
Sunny

Reputation: 14808

They are the same and do same thing

In View.java class

public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
        LayoutInflater factory = LayoutInflater.from(context);
        return factory.inflate(resource, root);
    }

and LayoutInflater.from(context) return the LayoutInflator object. which is same as calling getLayoutInflator() method.

public static LayoutInflater from(Context context) {
        LayoutInflater LayoutInflater =
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (LayoutInflater == null) {
            throw new AssertionError("LayoutInflater not found.");
        }
        return LayoutInflater;
    }

Upvotes: 1

Tafveez Mehdi
Tafveez Mehdi

Reputation: 456

Both are the same. The 2nd version is just a convenient and short method to do the task. If you see the source code of View.inflate() method, you find :

 /**
     * Inflate a view from an XML resource.  This convenience method wraps the {@link
     * LayoutInflater} class, which provides a full range of options for view inflation.
     *
     * @param context The Context object for your activity or application.
     * @param resource The resource ID to inflate
     * @param root A view group that will be the parent.  Used to properly inflate the
     * layout_* parameters.
     * @see LayoutInflater
     */
    public static View inflate(Context context, int resource, ViewGroup root) {
        LayoutInflater factory = LayoutInflater.from(context);
        return factory.inflate(resource, root);
    }

Which actually does the same job in the backend, the 1st method you mentioned does.

Upvotes: 6

Related Questions