我是编程新手,并试图理解为什么有时看起来对象是在没有“new”关键字的情况下实例化的。例如来自 google 的 android 教程的基本教程应用程序:
在 "Build an Intent"例如,使用 new
关键字创建 Intent
:
/** Called when the user taps the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
...
}
但后来在 "Display the Message" ,如果我理解正确的话,他们会这样创建一个 Intent
对象:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
...
}
并使用 getIntent() 方法。另外, getIntent() 方法在哪里定义?它是 Intent 类的方法吗?
还在上一节( https://developer.android.com/training/basics/firstapp/starting-activity.html )中,他们创建了一个新的 editText 但我仍然不明白为什么不使用“new”关键字:
EditText editText = (EditText) findViewById(R.id.editText);
感谢您的帮助。
最佳答案
很高兴得知您想开始学习代码..我已经添加了您的两个问题的解决方案,最好是继续前进,然后一切都会开始看起来合乎逻辑,一步一步..开始是最难的..
Intent Intent = getIntent();
这会实例化一个 Intent 对象,值来自函数 getIntent()。在下面的链接中您可以发现它是 Activity 类中的一个方法,并返回启动该 Activity 的 Intent。
https://developer.android.com/reference/android/app/Activity.html
EditText editText = (EditText) findViewById(R.id.editText);
这是对布局文件中定义的字段“editText”的引用。 您引用布局中的资源.. 更好、更清晰的是使用另一个命名..
EditText "你想如何命名字段"= (EditText) findViewById(R.id."布局中字段的名称")
按照下面的建议,尝试在线学习一些基础类(class),观看一些教程并坚持下去!
祝你好运!
关于java - 何时使用 "new"关键字 android API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49162749/