MohammadTofi
MohammadTofi

Reputation: 385

why I used layoutinflater in android?

I am a beginner developer in Android:

Could you explain what layoutinflater does and can you explain what it is used for in general and especially in this code?

I have this code :

 private class MyPagerAdapter extends PagerAdapter {

    public int getCount() {
        return 5;
    }

    public Object instantiateItem(View collection, int position) {

    *** LayoutInflater inflater = (LayoutInflater) collection.getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        int resId = 0;
        switch (position) {
        case 0:
            resId = R.layout.farleft;
            break;
        case 1:
            resId = R.layout.left;
            break;
        case 2:
            resId = R.layout.middle;
            break;
        case 3:
            resId = R.layout.right;
            break;
        case 4:
            resId = R.layout.farright;
            break;
        }

        View view = inflater.inflate(resId, null);

        ((ViewPager) collection).addView(view, 0);

        return view;
    }

Upvotes: 0

Views: 269

Answers (2)

nhaarman
nhaarman

Reputation: 100378

A LayoutInflater 'converts' an XML file to a View object, containing all the View children specified in that XML. You could also say that the 'flat' XML file is 'inflated' to a View.

See also LayoutInflater | Android Developers

Upvotes: 0

Moog
Moog

Reputation: 10193

The LayoutInflater service converts a stored copy of your XML layout into a collection of real instantiated views in the application process memory space.

  • The layout you created in your editor is saved as XML.
  • The XML is embedded into your app as a resource.
  • The layoutinflater reads the resource file.
  • It then creates the views you have specified as objects.
  • You can now manipulate the view objects from your code.

The Activity class does this process for you auto-magically when you call setContentView(int)

Upvotes: 4

Related Questions