Android this與Activity.this的區(qū)別
寫語句的時候有兩種情況:
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,終于有了結(jié)果(其實自己后面用了Java里ClassName.this和this 之前搜的是Activity.this,所以沒有結(jié)果,這點自己要靈活的提高自己的搜索能力了)。
在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是你當前對象的引用,在你的例子中你肯定在內(nèi)部類ClickEvent里面實現(xiàn)intent,他指向的是ClickEvent,而不是你要傳入的Activity。
Activity.this指向你所填寫的Activity名字的一個實例,也是引用。
其實這是java的基礎,我自己忘了。
this作為當前對象,直接用在Activity里面是沒問題的,當this在匿名內(nèi)部類中使用,當前的對象就變成new的內(nèi)部類,而你傳入的東西如果是整個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也行。
所以還是網(wǎng)友建議,全部用成Activity.this,清晰。
以上就是 Android this與Activity.this的區(qū)別的資料整理,后續(xù)繼續(xù)補充相關資料謝謝大家對本站的支持!
相關文章
Fragment里添加ListView不要用ListFragment
這篇文章主要介紹了Fragment里添加ListView不要用ListFragment,需要的朋友可以參考下2015-07-07Android控件ViewFlipper仿淘寶頭條垂直滾動廣告條
這篇文章主要為大家詳細介紹了Android控件ViewFlipper仿淘寶頭條垂直滾動廣告條,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05Android編程之canvas繪制各種圖形(點,直線,弧,圓,橢圓,文字,矩形,多邊形,曲線,圓角矩形)
這篇文章主要介紹了Android編程之canvas繪制各種圖形的方法,涉及Android使用Canvas類中常用繪圖方法的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-12-12android中Intent傳值與Bundle傳值的區(qū)別詳解
本篇文章是對android中Intent傳值與Bundle傳值的區(qū)別進行了詳細的分析介紹,需要的朋友參考下2013-05-05Android編程布局控件之AbsoluteLayout用法實例分析
這篇文章主要介紹了Android編程布局控件之AbsoluteLayout用法,結(jié)合實例形式簡單分析了Android絕對布局AbsoluteLayout的使用技巧,需要的朋友可以參考下2015-12-12