What is the correct way to get layout inflater in Android?

前端 未结 4 1405
终归单人心
终归单人心 2021-01-30 21:47

There is a way to get layoutInflater:

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

and

4条回答
  •  时光取名叫无心
    2021-01-30 22:08

    use outside of your activity

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

    Within your activity

         LayoutInflater inflater = getLayoutInflater();
    

    Check this

    If you open up the Android source you can see that the LayoutInflator.from method looks like so:

        /**
         * Obtains the LayoutInflater from the given context.
         */
        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;
        }
    

    and there is no difference

    As long as the Activity or Window that calls getLayoutInflater() has the same Context that would call getSystemService(), there is no difference.

提交回复
热议问题