您的位置:首页 > 移动开发 > Android开发

Android布局中LayoutInflater的使用(利用代码添加xml形式的Layout布局)

2012-07-21 17:24 597 查看

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的按钮下方

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐