kotlin EditText.text 属性访问语法问题

2020-01-02  本文已影响0人  折剑游侠

之前et.text = "text"报错没有深究,直接用setText()代替了。

回看一下问题出在哪里、TextView为什么没有这个问题。

et.text = "str"
et.text = Editable.Factory.getInstance().newEditable("str")
et.setText("str")
val s = et.text

et.text = "str"报错Type mismatch,EditText使用属性访问语法,得像第二行这样写。

反编译成java来看没有任何区别,都是调用TextView.setText()方法。

第二行的写法

public static class Factory {
        private static Editable.Factory sInstance = new Editable.Factory();
        public static Editable.Factory getInstance() {
            return sInstance;
        }

        public Editable newEditable(CharSequence source) {
            return new SpannableStringBuilder(source);
        }
}

Factory.newEditable()返回Editable,而Editable继承自CharSequence,用子类替代CharSequence没有问题。

为何kotlin非得要我们这么包装一下呢,下面看看EditText.getText()。

public Editable getText() {
        CharSequence text = super.getText();
        // This can only happen during construction.
        if (text == null) {
            return null;
        }
        if (text instanceof Editable) {
            return (Editable) super.getText();
        }
        super.setText(text, BufferType.EDITABLE);
        return (Editable) super.getText();
}

EditText.getText()返回Editable,所以第一行报错Type mismatch是匹配不上getText()方法。

使用属性访问语法时,编译器会同时检查get()和set(),这里要兼容get()将String向下转型为Editable。

当然,直接调用setText()是没有任何问题的。

TextView没有这个问题是因为TextView的get()方法返回CharSequence。而EditText继承TextView重写了getText()。

public CharSequence getText() {
        return mText;
}
上一篇下一篇

猜你喜欢

热点阅读