alexfu
12/12/2013 - 1:36 AM

A ContextWrapper that provides a custom Drawable for overscroll egde and glow. http://alexfu.github.io/blog/2013/12/11/customizing-edgeeffec

A ContextWrapper that provides a custom Drawable for overscroll egde and glow. http://alexfu.github.io/blog/2013/12/11/customizing-edgeeffect/

import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.util.Log;

/**
 * Custom ContextWrapper to modify certain Context related
 * actions/behaviors.
 */
public class MyContextWrapper extends ContextWrapper {

  private MyContextWrapper mResources;

  public MyContextWrapper(Context baseContext) {
    super(baseContext);
    Resources baseRes = baseContext.getResources();
    mResources = new MyContextWrapper(baseRes.getAssets(), baseRes.getDisplayMetrics(), baseRes.getConfiguration());
  }

  @Override
  public Resources getResources() {
    return mResources;
  }

  private class MyContextWrapper extends Resources {
    private int overscrollEdge, overscrollGlow;

    public MyContextWrapper(AssetManager assets, DisplayMetrics metrics, Configuration config) {
      super(assets, metrics, config);
      overscrollEdge = getPlatformDrawableId("overscroll_edge");
      overscrollGlow = getPlatformDrawableId("overscroll_glow");
    }

    @Override
    public Drawable getDrawable(int id) throws NotFoundException {
      // If the incoming id is equal to the com.android.internal.R.drawable.overscroll_edge
      // or com.android.internal.R.drawable.overscroll_glow ID, we'll provide our own Drawable.
      if(id == overscrollEdge) {
        return getBaseContext().getResources().getDrawable(R.drawable.overscroll_edge);
      } else if(id == overscrollGlow) {
        return getBaseContext().getResources().getDrawable(R.drawable.overscroll_glow);
      } else {
        return super.getDrawable(id);
      }
    }
    
    /**
     * Get the Android Drawable id that matches the given
     * drawable name.
     */
    private int getPlatformDrawableId(String name) {
      try {
        return ((Integer) Class.forName("com.android.internal.R$drawable").getField(name).get(null)).intValue();
      } catch (IllegalAccessException e) {
        Log.e("MyContextWrapper", e.getMessage());
        return 0;
      } catch (NoSuchFieldException e) {
        Log.e("MyContextWrapper", e.getMessage());
        return 0;
      } catch (ClassNotFoundException e) {
        Log.e("MyContextWrapper", e.getMessage());
        return 0;
      }
    }
  }
}