gpt4 book ai didi

android - 为 Android Lollipop 构建一个向后兼容的自定义 View (代码重复很少)

转载 作者:行者123 更新时间:2023-11-29 01:36:36 25 4
gpt4 key购买 nike

我想为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com