简体   繁体   中英

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;
    }

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM