我想创建一个没有字段的getter和setter。目前,我具有此功能:

/** Only the color component will be considered, alpha has no effect */
fun setCircleColor(@ColorInt color : Int){
    circlePaint.color = ColorUtils.setAlphaComponent(color, circlePaint.alpha)
}

理想情况下,我想要这样的东西
circleColor: @ColorInt Int
  get(){
    return circlePaint.color
  set(value){
    circlePaint.color = ColorUtils.setAlphaComponent(color, circlePaint.alpha)
  }

如您所见,我不想将circleColor存储在var中,但是仍然可以调用
myView.color = 0xFFaaaaaa而不是myView.setColor(0xFFaaaaaa)。这可能吗?

最佳答案

我建议按照您打算的方式实施它:

var circleColor: Int
    @ColorInt get() = circlePaint.color
    set(@ColorInt color) {
        circlePaint.color = ColorUtils.setAlphaComponent(color, circlePaint.alpha)
    }

10-06 04:55