finish()在OnClick事件中如何工作? [英] How does finish() work in OnClick event?

查看:184
本文介绍了finish()在OnClick事件中如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一个按钮的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆