您好,我刚刚开始学习 Android 应用程序开发,我正在观看很多教程,但没有一个教程真正一步步描述,所以我的问题是:
我创建了一个简单的应用程序,其中在 TextView
上包含一个 EditText
和一个 Button
我已将 android:onClick="onButtonClick"
添加到我的 Button
中,因此它将触发 onButtonClick
方法,现在,我想它从 EditText
打印出用户输入,所以我所做的是:
public void onButtonClick(View v){
Toast.makeText(v.getContext(), email.getText().toString(), Toast.LENGTH_SHORT).show();
}
但是为什么该方法必须包含 View v
?它是从哪里传递过来的?它包含什么?它包含我单击的按钮? v.getContext()
是做什么的?为什么我的应用程序在将 v.getContext()
替换为 this
时会执行相同的操作?
最佳答案
一下子有很多问题,但我尝试一一回答。
but why the method has to contain the View v ? where is it passed from ? and what does it contain ?
考虑documentation of View.OnClickListener :
View: The view that was clicked.
因此,您的假设是正确的,即已单击的是 View 。
and what does the v.getContext() do?
Toast#makeText 方法的第一个参数是 Context
。基本上,Context
是 Android 应用程序中全局信息的容器。 Toast
需要它检索信息来显示自己。
why my app does the same when replacing the v.getContext() with this ?
我假设您的方法驻留在Activity
中。安Activity是Context
的子类,可以用作参数。
关于Java - Android - view.getContext() 含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39558552/