The Layoutinflater function is to instantiate an XML layout file of layout as a view class object.
There are three ways to get Layoutinflater :
?
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.main, null ); LayoutInflater inflater = LayoutInflater.from(context); (该方法实质就是第一种方法,可参考源代码) View layout = inflater.inflate(R.layout.main, null ); LayoutInflater inflater = getLayoutInflater();(在Activity中可以使用,实际上是View子类下window的一个函数) View layout = inflater.inflate(R.layout.main, null ); |
It's been a little tangled . Setcontentview and inflate the difference to find some information. Wrote a small program looked under:
?
public class MyInflate
extends Activity{
private TextView tv;
public void OnCreate(Bundle savedInstanceState){
super
.onCreate(savedInstanceState);
//setContentView(R.layout.main);
//tv = (TextView) findViewById(R.id.tv);
LayoutInflater inflate = LayoutInflater.from(
this
);
View view = inflate.inflate(R.layout.main,
null
);
setContentView(view);
}
}
|
Both the commented out code and the code that are not commented out are the same in both cases.
Difference:
Setcontentview () once called , layout will display the UI immediately, and inflate will only form an object that is implemented in the view class, and then , if necessary, Setcontentview (view) is displayed. The interface is typically displayed in activity through setcontentview (), but if the control layout is set to operate in non- activity, this requires layoutinflater dynamic loading.
Public View Inflate (int resourece,viewgroup root)
Role: Populates a new view hierarchy from the specified XML resource file
ReSource: The ID of the layout of the view
Root: Rooted view of the resulting hierarchy
Return fills the root view of the hierarchy. If the parameter root is provided, then root is the root view, otherwise the root of the populated XML file is the root view.
The inflate functions are similar for the remaining several overloads .
Layoutinflater's Inflate function usage