我是编程新手,并试图理解为什么有时似乎在没有"new"关键字的情况下实例化对象。例如,来自谷歌安卓教程的基本教程应用程序:
在"构建意图"示例中,使用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);
...
}
但是稍后在"显示消息"中,如果我理解正确,他们会以这种方式创建一个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() 方法在哪里定义?这是来自意图类的方法?
同样在上一节(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 中的一个方法,并返回启动此活动的意图。
https://developer.android.com/reference/android/app/Activity.html
EditText editText = (EditText) findViewById(R.id.editText);
这是对布局文件中定义的字段"editText"的引用。 您引用布局中的资源。 更好和更清楚的是使用另一个命名..
EditText "How you want to name the field" = (EditText) findViewById (R.id."布局中字段的名称")
如下所述,尝试在线学习一些基础课程,观看一些教程并坚持下去!
祝你好运!