为什么这种铸造?

时间:2013-11-03 10:40:24

标签: android casting

我正在使用意图启动另一个活动,并使我的意图携带一些数据作为新创建的活动的额外内容。我正在按照教程来做这件事。

此数据实际上是从层次结构中第一个活动的文本字段中读取的,并作为额外活动传递给其他活动。所以我的代码就像:

//Make the intent   

Intent intent = new Intent(this, SecondActivity.class);

/* Find the text field (view) which contains the data, and save it into a newly created text field (view of the same type)*/

EditText editText = (EditText) findViewById(R.id.iden1); //******************************

//Read that view's string data into a string called message

String message= editmessage.getText().toString();

//copy this message into the extra named extra_name, of intent.

intent.putExtra(extra_name, message);

我的问题来自这句话:

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

我的问题是显式转换,即(EditText)。为什么我们将findViewById()返回的EditText视图(在layout.xml中定义并由android:id =“@ + id / iden1”标识)再次转换为EditText视图。此处视图editText的类型和layout.xml中创建的类型相同。那么这种类型铸造有什么意义呢?

2 个答案:

答案 0 :(得分:6)

关键是findViewById(int id)返回一个通用的View对象。此方法不会解析您的xml,以便了解您的视图类型。它只是由您的IDE构建的View文件建立了一个新的R.java对象(Eclipse,我想)。

需要来投射findViewById(int id)的结果,因为你没有投射EditText个对象,你投射了一个视图,其中只有EditText规范。

答案 1 :(得分:3)

findViewById返回View。如果需要使用派生类的方法,则需要进行强制转换。如果只需要使用基类的方法,则可以避免使用转换