Property getters & setters in custom view


#1

Hello Kotlin community,

recently i switched to kotlin from java in android development.
Everything works great so far, i have just one issue.

When i’m creating custom views and i define custom attributes, as android sdk says, i have to define getters and setters for that attributes.

For example if i have custom attribute with type String (app:anotherString=“string”)

public String getAnotherString() { 
     return mAnotherString;
}
 public void setAnotherString(String anotherString) { 
     this.mAnotherString = anotherString;
     ...
}

So i thought, that this can be replaced with property getters and setters like this :

var mAnotherString: String ? = null
      set(value) {
      ...
      }

But it just doesn’t work. Can someone explain me why?


#2

What is the error?

If you wants define property “anotherString”:

var anotherString: String = "string"

#3

There is no error, but as i said, i’m trying to implement my own custom attributes declared in attrs.xml.
This is a first step :

<declare-styleable name="MyCustomView">
    <attr name="anotherString" format="string" />
</declare-styleable>

next step is :

To provide dynamic behavior, expose a property getter and setter pair for each custom attribute.

as it is described here:
https://developer.android.com/training/custom-views/create-view.html#addprop

Problem is that it just does not work with property getters and setters in kotlin style, i need to define it with “java way” as i posted above.


#4

Copy the example code

public class JTest {
    private boolean mShowText;

    public boolean getShowText() {
        return mShowText;
    }

    public void setShowText(boolean showText) {
        mShowText = showText;
        invalidate();
        requestLayout();
    }
}

in a Kotlin file, the IDE should translate it to:

class JTest {
    var showText: Boolean = false
        set(showText) {
            field = showText
            invalidate()
            requestLayout()
        }
}

I hope this helps you.


#5

I forgot, the Kotlin way is:

var showText: Boolean by Delegates.observable(false) {
    prop, old, new ->
        invalidate()
        requestLayout()
    }

https://kotlinlang.org/docs/reference/delegated-properties.html#observable