gpt4 book ai didi

android - 为什么要进行这种类型的类型转换?

转载 作者:太空宇宙 更新时间:2023-11-03 11:58:10 27 4
gpt4 key购买 nike

我正在使用一个 Intent 来启动另一个 Activity ,并让我的 Intent 携带一些数据作为新创建的 Activity 的额外内容。我正在按照教程进行操作。

此数据实际上是从层次结构中第一个 Activity 的文本字段中读取的,并作为附加项传送到另一个 Activity 。所以我的代码会是这样的:

//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 View (在 layout.xml 中定义并由 android:id="@+id/iden1"标识)再次转换为 EditText View 。这里的view editText的类型和layout.xml中创建的是一样的。那么这种类型转换的意义何在?

最佳答案

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

需要转换findViewById(int id)的结果,因为您没有转换EditText对象,您转换的是View ,其中 EditText 只是一个规范。

关于android - 为什么要进行这种类型的类型转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19752026/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com