我想为 Android-L 构建一个支持四参数构造函数的自定义 View :
View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
理想情况下会调用 super 构造函数,然后进行一些初始化工作:
MyCustomView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
// initialize lots of static members here
}
并通过委托(delegate)给这个构造函数来实现其他构造函数:
例如
MyCustomView(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
问题是这在非 L 设备上会失败,因为不存在具有四个参数的 super 构造函数。
因此,我目前的解决方法是实现三参数和四参数构造函数(主要是复制和粘贴)并使用它。
有没有人看到更优雅的解决方案?
最佳答案
创建一个这样的方法:
private void init(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
// ...
}
然后让每个构造函数使用所需的参数调用 init()
方法。
关于android - 为 Android Lollipop 构建一个向后兼容的自定义 View (代码重复很少),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27570725/