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

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


  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值