当前位置: 移动技术网 > IT编程>移动开发>Android > Android this与Activity.this的区别

Android this与Activity.this的区别

2019年07月24日  | 移动技术网IT编程  | 我要评论

人民防线,mm公寓最新网址,古典文学网

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

toast.maketext(alarmactivity.this,"闹钟取消", toast.length_short); 
 <pre name="code" class="java">toast.maketext(this,"闹钟5秒后启动", toast.length_short); 

           用英文在google搜what‘s difference between this and activity.this,终于有了结果(其实自己后面用了java里classname.this和this 之前搜的是activity.this,所以没有结果,这点自己要灵活的提高自己的搜索能力了)。

      在stackoverflow找到了答案:

http://stackoverflow.com/questions/10102151/whats-the-difference-between-this-and-activity-this

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名字的一个实例,也是引用。

    其实这是java的基础,我自己忘了。

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也行。

    所以还是网友建议,全部用成activity.this,清晰。

以上就是 android this与activity.this的区别的资料整理,后续继续补充相关资料谢谢大家对本站的支持!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网