问题描述
你好,我是 android 的新手,在活动上下文中我对此关键字感到困惑.这是一个代码段,当按下按钮时,该代码段仅打印到屏幕上.但是工作室提出了一个问题.
Hello I'm new to android and I'm confused with this keyword in activity contexts. Here is a code snippet which simply prints to the screen when a button is pressed. But the studio is raising an issue.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("My app","onCreate is called");
Toast1("onCreate");
Button btn=(Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("My app","Button is pressed");
Toast.makeText(this,"Button pressed",Toast.LENGTH_SHORT).show();//Here is a error
}
});
}
如何知道此关键字引用的活动或类别?
How to know which activity or class the this keyword referencing?
推荐答案
在匿名类内部,this
引用匿名类的块.要引用包含匿名类的Activity类,您需要在this
关键字之前附加类名称和.
Inside anonymous class, this
refers to the block of the anonymous class. To refer to the Activity class which contains the anonymous class, you need to append the class name and .
before the this
keyword
ActivityClassName.this
Toast
要么需要要显示活动的上下文,要么需要应用程序的上下文
Toast
either requires the context of the activity on which it is to be displayed or the context of the application
使用活动上下文敬酒
Toast.makeText(Activityname.this,"Button pressed",Toast.LENGTH_SHORT).show();
注意:如果您的Toast
在任何匿名类中,则需要使用ActivityName.this
.如果不是这种情况,只需使用this
即可完成工作.
Note: If your Toast
is inside any anonymous class, then you need to use ActivityName.this
. If that's not the case, simply using this
would do the job.
使用应用程序上下文进行烤面包
Toast.makeText(getApplicationContext(),"Button pressed",Toast.LENGTH_SHORT).show();
这篇关于匿名课程中的活动名称是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!