-1

我刚刚遇到了一些我以前从未见过的语法,因为在谷歌上很难找到答案,我决定问一个问题。有问题的声明是:

EditText editText = (EditText) findViewById(R.id.edit_message);

我知道代码正在创建 EditText 类的对象“editText”,但我之前从未见过等号之后的代码。我最好的猜测是它正在运行 findViewById() 方法,并且该消息存在于 EditText 类中,这就是为什么括号中的 EditText 是必要的?

我知道我现在可能应该知道这种语法,因为我刚刚在 CS 大学完成了我的第一门 Java 课程,但不幸的是,我们从未被介绍过这样的东西。

非常感谢。

4

3 回答 3

2

findViewById返回 a View,所以

EditText editText = findViewById(R.id.edit_message);

将抛出一个编译异常,告诉您不能将 a 分配ViewEditText变量。

(EditText)View类型转换为EditText,换句话说,您告诉编译器将 的结果分配给 是安全findViewByIdEditText,因为您期望edit_message视图实际上是一个EditText对象。

最后,如果您对编译器“撒谎”并且edit_message不是.EditTextClassCastException

于 2013-10-12T10:45:17.177 回答
2

This is a typecast, forcing the compiler to assume that the result returned by the function findViewById is an EditText object.

If it is of another type, you'd get a runtime error.

Here's the offical docs on the subject.

于 2013-10-12T10:35:48.047 回答
0

It is used for creating textbox in which you can type your query, in this code findviewbyid is an method which return an object while (EditText) is used for casting and as here the returned object is of type edittext thats why we are save in an variable edittext of type EDITTEXT.

于 2013-10-12T10:36:41.400 回答