2017-10-10 56 views
1

我需要的情況下多次在我的片段:許多「getContext()」或一個私有上下文= getContext()並使用它?

... 
    account.restore(getContext()); 
    ... 
    dbHelper = new DBHelper(getContext()); 
    ... 
    DiskLruBasedCache.ImageCacheParams cacheParams = new DiskLruBasedCache.ImageCacheParams(getContext(), "CacheDirectory"); 
    ... 
    mImageLoader = new SimpleImageLoader(getContext(), cacheParams); 
    ... 
    Toast.makeText(getContext(), "err: " + error, Toast.LENGTH_LONG).show(); 
    ... 
    RecyclerView.LayoutManager layoutManager = new CustomLayoutManager(getContext()); 
    ... 

或者我應該初始化一次,然後使用它。

什麼是最佳方式?

+1

'private Context = getContext()'不起作用 –

+0

'Private Context = getContext()'不會編譯。 –

回答

2

這主要是一個偏好問題。無論你需要什麼,你都可以撥打getContext() - 無需擔心演奏開銷。或者,您可以在onCreate方法中指定private Context context字段。或者,如果一個特定的方法有多個用途,則創建一個局部變量。

如果getContext有可能很慢,那麼你應該確實隱藏它,但它實際上只是一個簡單的存取器(幾乎 - 它在內部執行一點間接尋址)。

去找你發現最具可讀性的東西。

+0

但'getContext()'在片段內不起作用。 –

+0

是的,它會的。你有沒有嘗試過? –

+1

OP已經在使用'getContext()',只是問是否有意義存儲它。 –

相關問題