服务器之家

服务器之家 > 正文

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

时间:2021-05-28 15:37     来源/作者:bigconvience

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

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

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

?
1
2
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View child = inflater.inflate(R.layout.child, null);

或者:

?
1
2
LayoutInflater inflater = LayoutInflater.from(context);
View child = inflater.inflate(R.layout.child, null);

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

?
1
View child = getLayoutInflater().inflate(R.layout.child, item, false);

或者:

?
1
2
3
View view;
LayoutInflater inflater = (LayoutInflater)  getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.mylayout, null);

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

3、使用View的静态方法:

?
1
View view=View.inflate(context, R.layout.child, null)

inflate实现源码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
 * 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的包装,可参考以下源码:

?
1
2
3
4
5
6
7
8
9
10
11
/**
 * 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程序设计有所帮助。

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
2021德云社封箱演出完整版 2021年德云社封箱演出在线看
2021德云社封箱演出完整版 2021年德云社封箱演出在线看 2021-03-15
返回顶部