finish()在OnClick事件中如何工作? [英] How does finish() work in OnClick event?
问题描述
我有一个带有一个按钮的Activity
来退出Activity
.
I have an Activity
with one button to quit the Activity
.
通过layout.xml
,我必须将OnClick
事件设置为cmd_exit
,并且对'this.finish()'的调用可以正常工作
Through the layout.xml
I have to set the OnClick
event to cmd_exit
and a call to 'this.finish()' works fine
public void cmd_exit(View editLayout){
this.finish();
}
,但是当我添加OnClickListener
时
cmd_exit = (Button) this.findViewById(R.id.cmd_ExitApp);
cmd_exit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
this.finish()
给出错误.只能是finish()
.
我知道finish()
位于Activity
类中,所以我的问题是它在第二个代码段中如何工作?
I understand that finish()
lives in the Activity
class so my question is how is it working in the second snippet?
推荐答案
创建OnClickListener
作为匿名类时,this
关键字引用该侦听器实例,而不是封闭的类.您可以改用YourActivityClassName.this
.您也可以省略this
,并且由于OnClickListener
没有finish()
方法,因此将使用Activity
.
When you've created an OnClickListener
as an anonymous class, the this
keyword refers to that listener instance rather than the enclosing class. You could use YourActivityClassName.this
instead. You could also just omit the this
, and since OnClickListener
doesn't have a finish()
method so the Activity
one will be used.
这篇关于finish()在OnClick事件中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!