当前位置: 移动技术网 > 移动技术>移动开发>Android > Android开发之获取LayoutInflater对象的方法总结

Android开发之获取LayoutInflater对象的方法总结

2019年07月24日  | 移动技术网移动技术  | 我要评论

本文实例讲述了android开发之获取layoutinflater对象的方法。分享给大家供大家参考,具体如下:

在写android程序时,有时候会编写自定义的view,使用inflater对象来将布局文件解析成一个view。本文主要目的是总结获取layoutinflater对象的方法。

1、若能获取context对象,可以有以下几种方法:

layoutinflater inflater = (layoutinflater)context.getsystemservice(context.layout_inflater_service);
view child = inflater.inflate(r.layout.child, null);

或者:

layoutinflater inflater = layoutinflater.from(context);
view child = inflater.inflate(r.layout.child, null);

2、在一个activity中,可以有以下方法:

view child = getlayoutinflater().inflate(r.layout.child, item, false);

或者:

view view;
layoutinflater inflater = (layoutinflater)  getcontext().getsystemservice(context.layout_inflater_service);
view = inflater.inflate(r.layout.mylayout, null);

方法1和方法2其实都是对context().getsystemservice()的使用

3、使用view的静态方法:

view view=view.inflate(context, r.layout.child, null)

inflate实现源码如下:

/**
 * 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);
}

layoutinflater.from(context)实际上是对方法1的包装,可参考以下源码:

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

更多关于android相关内容感兴趣的读者可查看本站专题:《android开发入门与进阶教程》、《android控件用法总结》、《android短信与电话操作技巧汇总》及《android多媒体操作技巧汇总(音频,视频,录音等)

希望本文所述对大家android程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网