你的位置:首页 > 信息动态 > 新闻中心
信息动态
联系我们

View(二):自定义举例之继承控件

2021/12/15 11:34:29

以继承Layout为例

1.自定义一些我们需要用的属性,在res/values/attrs.xml里

<declare-styleable name="xxxxx">     这里名字随便取啦,但是后面java文件里会用到哦
        <attr name="animation_time" format="integer" />
        <attr name="background" format="reference" /> 
    </declare-styleable>

refrence指参考资源id,比如@drawable/图片ID

2.新建一个java文件作为我们的自定义view,继承某个Layout,比如FrameLayout

写构造函数,一般我们会三个都写。具体为啥写三个见下面的链接https://blog.csdn.net/qq_41100045/article/details/121247944

public class MyFrameLayout extends FrameLayout {

    public MyFrameLayout(Context context) {
        this(context, null);
    }

    public MyFrameLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyFrameLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        mInflater = LayoutInflater.from(context);
        init(attrs);
    }
}