创建自定义控件

新建 TitleLayout 继承自 LinearLayout

public class TitleLayout extends LinearLayout {
    public TitleLayout(Context context , AttributeSet attrs){//重写构造器
        super(context,attrs);
        LayoutInflater.from(context).inflate(R.layout.topbar,this);
        //LayoutInflater.from()构建LayoutInflater对象,对象的inflate方法,第一个参数布局文件的id,第二个参数,this<==>TitleLayout
    }
}

需要注意的是在引用时候必须使用完整类名。

岑忠满的博客新站点 https://cenzm.xyz
原文地址:https://www.cnblogs.com/cenzhongman/p/6030268.html