3 回答

TA貢獻(xiàn)1719條經(jīng)驗(yàn) 獲得超6個(gè)贊
View.getContext()
:返回視圖當(dāng)前運(yùn)行的上下文。通常是當(dāng)前活躍的活動(dòng)。 Activity.getApplicationContext()
:返回整個(gè)應(yīng)用程序的上下文(所有活動(dòng)都在其內(nèi)部運(yùn)行的進(jìn)程)。如果您需要一個(gè)與整個(gè)應(yīng)用程序的生命周期相關(guān)聯(lián)的上下文,而不僅僅是當(dāng)前的活動(dòng),請(qǐng)使用它而不是當(dāng)前的活動(dòng)上下文。 ContextWrapper.getBaseContext()
如果需要從另一個(gè)上下文中訪問上下文,則使用ContextWrapper。從ContextWrapper內(nèi)部引用的上下文通過getBaseContext()訪問。

TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊
getContext()
getApplicationContext()
getBaseContext()
ContextWrapper
ContextWrapper
Context
ContextWrapper wrapper = new ContextWrapper(context);
ContextWrapper
myActivity
View
myActivity
:
ContextWrapper customTheme = new ContextWrapper(myActivity) { @Override public Resources.Theme getTheme() { return someTheme; }}View myView = new MyView(customTheme);
ContextWrapper
Context
openFileInput()
, getString()
sendBroadcast()
, registerReceiver()
checkCallingOrSelfPermission()
getFilesDir()
). ContextWrapper
ContextWrapper
Service
, Activity
Application
:
public class CustomToast { public void makeText(Context context, int resId, int duration) { while (context instanceof ContextWrapper) { context = context.baseContext(); } if (context instanceof Service)) { throw new RuntimeException("Cannot call this from a service"); } ... }}
class MyCustomWrapper extends ContextWrapper { @Override public Drawable getWallpaper() { if (BuildInfo.DEBUG) { return mDebugBackground; } else { return getBaseContext().getWallpaper(); } }}

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超18個(gè)贊
getApplicationContext()
getBaseContext()
getContext()
添加回答
舉報(bào)