采用布局填充器把xml文件转换成view对象
3种方式将xml中转为view
一、3种方式将xml中转为view
3种方式将xml中转为view
一、3种方式将xml中转为view
方式一:LayoutInflater inflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
最原始的方式
// 方式一:原始方式:Context.getSystemService("服务名")
LayoutInflater inflater = (LayoutInflater) MainActivity. this .getSystemService(Context. LAYOUT_INFLATER_SERVICE );
// View list_item = inflater.inflate(R.id.list_item, null);//不是id中的list_item而是layout中的list_item
View list_item = inflater.inflate(R.layout. list_item , null ); // 参数2表示是否独立
方式二:LayoutInflater inflater2 = LayoutInflater.from(MainActivity.this);
底层是方式一
// 方式二:LayoutInflater.from(Context)
// LayoutInflater inflater2 = LayoutInflater.from(MainActivity.this);
// View list_item = inflater2.inflate(R.layout.list_item, null);
底层实现:
public static LayoutInflater from (Context context) {
LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context. LAYOUT_INFLATER_SERVICE );
if (LayoutInflater == null ) {
<span style="white-space:pre"> </span>throw new AssertionError( "LayoutInflater not found." );
}
return LayoutInflater;
}
方式三:View list_item = View.inflate(MainActivity.this, R.layout.list_item, null);
底层是方式二和方式一
public static View inflate (Context context, int resource, ViewGroup root) {
LayoutInflater factory = LayoutInflater.from(context);
return factory.inflate(resource, root);
}