Skip to content

Instantly share code, notes, and snippets.

@pskink
Last active November 18, 2015 21:56
Show Gist options
  • Save pskink/5be676cb88d34dfb6cb5 to your computer and use it in GitHub Desktop.
Save pskink/5be676cb88d34dfb6cb5 to your computer and use it in GitHub Desktop.
abstract class DecoratedDrawable extends LevelListDrawable {
public DecoratedDrawable(Context ctx, int resId) {
TypedArray typedArray = ctx.obtainStyledAttributes(new int[] {resId});
Drawable drawable = typedArray.getDrawable(0);
typedArray.recycle();
if (drawable == null) {
drawable = ctx.getResources().getDrawable(resId);
}
init(drawable);
}
public DecoratedDrawable(Drawable drawable) {
init(drawable);
}
private void init(Drawable drawable) {
addLevel(0, 10000, drawable);
};
@Override
protected boolean onLevelChange(int level) {
invalidateSelf();
return super.onLevelChange(level);
}
@Override
public void draw(Canvas canvas) {
onPreDraw(canvas);
super.draw(canvas);
onPostDraw(canvas);
}
protected void onPreDraw(Canvas canvas) {};
protected void onPostDraw(Canvas canvas) {};
}
// sample implementation
class ErrorDrawable extends DecoratedDrawable {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
public ErrorDrawable(Context ctx, int resId) {
super(ctx, resId);
}
@Override
protected void onPreDraw(Canvas canvas) {
int lvl = getLevel();
paint.setColor(lvl < 5 ? (lvl < 3? 0xffff0000 : 0xffff8800) : 0xff00ff00);
canvas.drawCircle(0, 0, getBounds().height() / 3f, paint);
}
}
// sample usage
final EditText editText = (EditText) findViewById(R.id.edit);
final Drawable d = new ErrorDrawable(this, android.R.attr.editTextBackground);
d.setLevel(editText.length());
editText.setBackground(d);
TextWatcher watcher = new TextWatcher() {
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override public void afterTextChanged(Editable s) {
d.setLevel(s.length());
}
};
editText.addTextChangedListener(watcher);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment