2015-07-13 33 views
9

通過一些所謂的「好」來源來了解Android中的上下文處理的細節和技巧我多次遇到一種模式,理解。爲什麼在「活動」中直接使用ContextWrapper而不是隱式上下文

當你同樣可以很好地使用隱式上下文時,使用ContextWrapper有什麼好處?

例如爲什麼使用在活性的方法,下面的(直接在一個Activity類中定義)

... 
ContextWrapper cw = new ContextWrapper(getApplicationContext()) 
File filesDir = cw.getFilesDir(); 
... 

即使getFilesDir()在ContextWrapper類被定義的,而不是僅僅

... 
File filesDir = getFilesDir(); 
... 

Activity無論如何都是ContextWrapper的一個子類,所以你可以直接訪問該方法。

那麼,什麼潛在的問題(我看不到)這是否增加了複雜性地址?

+0

'Application'延伸'ContextWrapper'以及。 – tynn

回答

6

我會說(我可能是錯的),在你提出的情景(和上下文)可能沒有區別。本來可以使用getApplicationContext().getFilesDir()

但是,我相信ContextWrapper可能在其他情況下有用。據我所知,這是適配器模式。您可能希望只爲同時代理所有其他您在傳遞原始上下文引用某些方法提供了不同的行爲

退房這段代碼從RemoteViews

// RemoteViews may be built by an application installed in another 
// user. So build a context that loads resources from that user but 
// still returns the current users userId so settings like data/time formats 
// are loaded without requiring cross user persmissions. 
final Context contextForResources = getContextForResources(context); 
Context inflationContext = new ContextWrapper(context) { 
    @Override 
    public Resources getResources() { 
     return contextForResources.getResources(); 
    } 
    @Override 
    public Resources.Theme getTheme() { 
     return contextForResources.getTheme(); 
    } 
}; 
相關問題