我目前正在 Android-Studio 中研究 Java。 我偶然发现了一个我不明白的现象。当我尝试调用 EditText 类的 getText() 时,我首先需要创建 EditText 类的实例。有人可以解释这是为什么吗?
这个有效:
EditText editText = findViewById(R.id.editText);
editText.getText();
这不是:
findViewById(R.id.editText).getText();
最佳答案
那是因为View#findViewById返回的对象类型是通用的,通常会自动转换为引用类型(在您的情况下为 EditText
)(如果给定的话)。
引用文档:
Note: In most cases -- depending on compiler support -- the resulting view is automatically cast to the target class type. If the target class type is unconstrained, an explicit cast may be necessary.
如果您的编译器不知道 findViewById(R.id.editText)
是 EditText
类型,它将不允许您调用 getText
(即 android.view.View
没有 getText
方法)。
关于java - 为什么我需要为 EditText.getText() 创建一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56132635/