1.什么是LayoutInflater
This class is used to instantiate layout XML file into its corresponding View objects.
这个类是代码形式,把xml类型的布局转化成相应的View对象
2.如何获得LayoutInflater(3种方式)
LayoutInflater inflater = LayoutInflater.from(context);
LayoutInflater inflater = getLayoutInflater();
LayoutInflater inflater = (LayoutInflater)context.getSystemService(LAYOUT_INFLATER_SERVICE);
3.如何使用LayoutInflater
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup viewGroup = (ViewGroup)this.getLayoutInflater().inflate(R.layout.main, null);
SurfaceView view1 = new MySurfaceView(this,Color.RED);//可用其他View代替
SurfaceView view2 = new MySurfaceView(this,Color.BLUE);//可用其他View代替
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(40, 40);
//view2.setZOrderOnTop(true);
viewGroup.addView(view1);
this.setContentView(viewGroup);
//this.addContentView(view2, lp);
}
If no layout parameters are already set on the child, the default parameters for this ViewGroup are set on the child.
在Activity中使用,因为R.layout.main为LinearLayout,通过inflate获得的ViewGroup是LinearLayout对象,所以直接addView的话会是默认的layout方式,红色的surfaceView加到了R.layout.main的按钮下方