TShopping

 找回密碼
 註冊
搜索
查看: 1715|回復: 0

[教學] Android問題之this與Activity.this的區別

[複製鏈接]
發表於 2016-10-19 06:08:11 | 顯示全部樓層 |閱讀模式
 
Push to Facebook

寫語句的時候有兩種情況:
  1. Toast.makeText(AlarmActivity.this,"闹钟取消", Toast.LENGTH_SHORT);  
  2. 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/questio ... s-and-activity-this
  1. Intent intent = new Intent(this, SecondActivity.class);  
  2.   
  3.     eclipse error: The method setClass(Context, Class) in the type Intent is not applicable for the arguments (FirstActivity.ClickEvent, Class)  
  4.   
  5. 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了。

  1. Button b.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {  
  2.     public void onClick(DialogInterface dialog, int which) {  
  3.         Toast.makeText(AlarmActivity.this,"鬧鐘5秒後啟動", Toast.LENGTH_SHORT);     
  4. }};  
複製代碼


所以在這裡面需要指定是哪個activity的,Toast的那條語句移到外面,刪掉AlarmActivity也行。

    所以還是網友建議,全部用成Activity.this,清晰。

 

臉書網友討論
*滑块验证:
您需要登錄後才可以回帖 登錄 | 註冊 |

本版積分規則



Archiver|手機版|小黑屋|免責聲明|TShopping

GMT+8, 2024-3-19 16:20 , Processed in 0.089672 second(s), 23 queries .

本論壇言論純屬發表者個人意見,與 TShopping綜合論壇 立場無關 如有意見侵犯了您的權益 請寫信聯絡我們。

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表