为什么要进行这种类型的铸造

为什么要进行这种类型的铸造

本文介绍了为什么要进行这种类型的铸造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个意图来启动另一个活动,并使我的意图携带一些数据作为新创建的活动的补充。我正在按照一个教程进行操作。

I am using an intent to start another activity, and making my intent carry some data as an extra to the newly created activity. I am following a tutorial to do that.

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

This data is actually read from a text field in the first activity in the hierarchy, and carried to the other activity as an extra. so my code will be like:

//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);

我的问题来自以下语句:

My question is from this statement:

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

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

My question is explicit casting i.e. (EditText). Why are we casting the EditText view (which was defined in layout.xml and was identified by android:id="@+id/iden1") returned by findViewById()to an EditText view again. The type of the view editText here and the one created in layout.xml is the same. So what is the point of this type-casting?

推荐答案

重点是 findViewById(int id )返回一个普通的 View 对象。此方法不会解析您的xml以便了解您的视图的类型。它只是根据您的 R.java 文件建立的关系创建一个新的 View 对象IDE(我想是Eclipse)。

The point is that findViewById(int id) returns a generic View object. This method doesn't parse your xml in order to understand what kind of type is your view. It just makes a new View object from the relationship put in place by your R.java file, built up by your IDE (Eclipse, I suppose).

需要强制转换 findViewById(int id)的结果code>,因为您没有投射 EditText 对象,而是投射了一个View,其中的 EditText 只是一个规范。

You need to cast the result of findViewById(int id) because you're not casting an EditText object, your casting a View, of which EditText is only a specification.

这篇关于为什么要进行这种类型的铸造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 22:31