Skip to content

Instantly share code, notes, and snippets.

@alexfu
Last active November 10, 2017 10:49
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save alexfu/7921852 to your computer and use it in GitHub Desktop.
Save alexfu/7921852 to your computer and use it in GitHub Desktop.
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;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment