Activity.this 与this的区别

来源:互联网 发布:linux怎么打开防火墙 编辑:程序博客网 时间:2024/06/06 16:54

首先我们知道 在Java还是c++中 this指向的是当前的对象

写语句的时候有两种情况:

     Toast.makeText(AlarmActivity.this,"闹钟取消", Toast.LENGTH_SHORT);       <pre name="code" class="java">Toast.makeText(this,"闹钟5秒后启动",         Toast.LENGTH_SHORT);          Intent intent = new Intent(this, SecondActivity.class);       eclipse error: The method setClass(Context, Class) in the type Intent is not applicable for the arguments (FirstActivity.ClickEvent, Class)   Intent intent = new Intent(FirstActivity.this, SecondActivity)      this refers to your current object. In your case you must have implemented the intent in an inner class ClickEvent, and thats what it points to.    Activity.this points to the instance of the Activity you are currently in.

this是你当前对象的引用,在你的例子中你肯定在内部类ClickEvent里面实现intent,他指向的是ClickEvent,而不是你要传入的Activity。
Activity.this指向你所填写的Activity名字的一个实例,也是引用。

this作为当前对象,直接用在Activity里面是没问题的,当this在匿名内部类中使用,当前的对象就变成new的内部类,而你传入的东西如果是整个Activity的话,就要Activity.this了。

 Button b.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {       public void onClick(DialogInterface dialog, int which) {            Toast.makeText(AlarmActivity.this,"闹钟5秒后启动", Toast.LENGTH_SHORT);     }};  

所以在这里面需要指定是哪个activity的,Toast的那条语句移到外面,删掉AlarmActivity也行。