源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2020-03-13 23:06 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Android开发之获取LayoutInflater对象的方法总结
本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/410.htm]Android开发入门与进阶教程[/url]》、《[url=http://www.1sucai.cn/Special/124.htm]Android控件用法总结[/url]》、《[url=http://www.1sucai.cn/Special/394.htm]Android短信与电话操作技巧汇总[/url]》及《[url=http://www.1sucai.cn/Special/398.htm]Android多媒体操作技巧汇总(音频,视频,录音等)[/url]》 希望本文所述对大家Android程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部