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é)果(其實(shí)自己后面用了Java里ClassName.this和this 之前搜的是Activity.this,所以沒有結(jié)果,這點(diǎn)自己要靈活的提高自己的搜索能力了)。
在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是你當(dāng)前對象的引用,在你的例子中你肯定在內(nèi)部類ClickEvent里面實(shí)現(xiàn)intent,他指向的是ClickEvent,而不是你要傳入的Activity。
Activity.this指向你所填寫的Activity名字的一個實(shí)例,也是引用。
其實(shí)這是java的基礎(chǔ),我自己忘了。
this作為當(dāng)前對象,直接用在Activity里面是沒問題的,當(dāng)this在匿名內(nèi)部類中使用,當(dāng)前的對象就變成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ù)補(bǔ)充相關(guān)資料謝謝大家對本站的支持!
- Android開發(fā)仿掃一掃實(shí)現(xiàn)拍攝框內(nèi)的照片功能
- Android設(shè)計(jì)模式系列之工廠方法模式
- Android中用RxJava和ViewPager實(shí)現(xiàn)輪播圖
- Android設(shè)計(jì)模式系列之單例模式
- Android設(shè)計(jì)模式系列之組合模式
- Android中的設(shè)計(jì)模式
- Android開發(fā)性能優(yōu)化總結(jié)
- Android 對話框sweet-alert-dialog
- Android string-array數(shù)據(jù)源簡單使用
- Android 解決build path errors的問題
相關(guān)文章
Android獲取WebView加載url的請求錯誤碼 【推薦】
這篇文章主要介紹了Android獲取WebView加載url的請求錯誤碼 ,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-06-06
android開發(fā)基礎(chǔ)教程—SharedPreferences讀寫
本文介紹SharedPreferences的讀與寫的實(shí)現(xiàn)思路,感興趣的朋友可以了解下2013-01-01
Android獲取雙卡雙待手機(jī)的SIM卡信息示例代碼
這篇文章主要給大家介紹了關(guān)于Android獲取雙卡雙待手機(jī)的SIM卡信息的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對各位Android開發(fā)者們具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-11-11
Android RecyclerView的Item點(diǎn)擊事件實(shí)現(xiàn)整理
這篇文章主要介紹了Android RecyclerView的Item點(diǎn)擊事件實(shí)現(xiàn)整理的相關(guān)資料,需要的朋友可以參考下2017-01-01
php 異步調(diào)用方法實(shí)現(xiàn)示例
客戶端與服務(wù)器端是通過HTTP協(xié)議進(jìn)行連接通訊,客戶端發(fā)起請求,服務(wù)器端接收到請求后執(zhí)行處理,并返回處理結(jié)果2014-01-01
Flutter?Android多窗口方案落地實(shí)戰(zhàn)
這篇文章主要為大家介紹了Flutter?Android多窗口方案落地實(shí)戰(zhàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02

