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

标签 android android-custom-view custom-view

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

相关文章:

android - 做提醒app有什么用?

java错误堆栈溢出

android - 圆角ItemDecoration

ios - UIAlertController 中的自定义 View

android - 在运行时从另一个应用程序获取自定义 View

android - 自定义EditText垂直对齐方式

android - 如何在 Android 现有的 csv 文件中存储新值?

android - jQuery mobile,检测用户何时向右滑动图像

android - 如何使用自定义 View 创建通知,但具有原生外观?

android - 无法创建带有单击监听器的自定义按钮