Android LayoutInflater Introduction

April 2, 2018 Oclemy Android Layout 0 minutes, 58 seconds

LayoutInflater is a class used to inflater XML layouts ino the android.view.View object. This is important since android applications primarily apply creation of user interfaces declaratively using XML(eXtensible Markup Language).

Characteristics of LayoutInflater

  1. It's a public class hence can be used by other packages.
  2. It's an abstract class hence is never used directly.
public abstract class LayoutInflater{..}
  1. It resides in the android.view package since it's primary used to work with views.
package android.view;

Roles of LayoutInflater

  1. Inflate XML layouts into android.view.View object.

Obtaining a LayoutInflater instance

As an abstract class LayoutInflater is never used directly. Instead we use methods provided by either an activity or a context class. Here's how we retrieve those:

  1. Activity.getLayoutInflater
  2. Context.getLayoutInflater . This is the most commonly used way. It provides us with a LayoutInflater instance already hooked up to the current context and configured for the device we are running on.

e.g

LayoutInflater inflater= (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

Inflating a View using LayoutInflater

After obtaining the LayoutInflater instance we can the inflate a Layout in the following manner:

View myView=inflater.inflate(R.layout.custom_layout,parent,false);

Comments