2012-04-13 30 views
9

Android có duy trì bộ nhớ cache của các tài nguyên có thể vẽ và sử dụng lại chúng hay thực hành tốt để tải trước tất cả các bản vẽ có thể được gán động cho các tiện ích khác nhau?Có bất kỳ lý do nào để tải trước nội dung có thể rút từ tài nguyên không?

Ví dụ:

public static final int[] SETS = { 
     R.drawable.set0, R.drawable.set1, R.drawable.set2, 
     R.drawable.set3, R.drawable.set4, R.drawable.set5, R.drawable.set6, 
     R.drawable.set7, R.drawable.set8, R.drawable.set9, R.drawable.set10}; 
public Drawable[] sets; 

void init() { 
    load(sets, SETS); 
} 

public void load(Drawable[] d, int[] ids) { 
    for (int i = 0; i < ids.length; i++) { 
     if (ids[i] == 0) 
      d[i] = null; 
     else 
      d[i] = context.getResources().getDrawable(ids[i]); 
    } 
} 

Trả lời

9

này có mùi giống như một pre-tối ưu hóa không cần thiết. Tuy nhiên, android không có bộ nhớ cache để bạn không phải tải trước chúng. Mã có liên quan từ ApplicationContext

/*package*/ Drawable loadDrawable(TypedValue value, int id) 
      throws NotFoundException { 
     . 
     . 
     . 

     final long key = (((long) value.assetCookie) << 32) | value.data; 
     Drawable dr = getCachedDrawable(key); 

     if (dr != null) { 
      return dr; 
     } 

     . 
     . 
     . 

     if (dr != null) { 
      dr.setChangingConfigurations(value.changingConfigurations); 
      cs = dr.getConstantState(); 
      if (cs != null) { 
       if (mPreloading) { 
        sPreloadedDrawables.put(key, cs); 
       } else { 
        synchronized (mTmpValue) { 
         //Log.i(TAG, "Saving cached drawable @ #" + 
         //  Integer.toHexString(key.intValue()) 
         //  + " in " + this + ": " + cs); 
         mDrawableCache.put(key, new WeakReference<Drawable.ConstantState>(cs)); 
        } 
       } 
      } 
     } 

     return dr; 
    } 

    private Drawable getCachedDrawable(long key) { 
     synchronized (mTmpValue) { 
      WeakReference<Drawable.ConstantState> wr = mDrawableCache.get(key); 
      if (wr != null) { // we have the key 
       Drawable.ConstantState entry = wr.get(); 
       if (entry != null) { 
        //Log.i(TAG, "Returning cached drawable @ #" + 
        //  Integer.toHexString(((Integer)key).intValue()) 
        //  + " in " + this + ": " + entry); 
        return entry.newDrawable(this); 
       } 
       else { // our entry has been purged 
        mDrawableCache.delete(key); 
       } 
      } 
     } 
     return null; 
    } 
+1

Có cách nào để tắt bộ đệm ẩn không? Tôi nhận được một lần duy nhất có thể kéo và thay đổi độ bóng của nó. Tất cả đều kết thúc cùng một màu sắc. Rất bực bội. – astryk

+0

đó là lý do tại sao có mutate() trên drawables ... – headsvk

Các vấn đề liên quan