Skip to content

Instantly share code, notes, and snippets.

@esabook
Last active February 8, 2020 07:41
Show Gist options
  • Save esabook/4f3c37fe0046f245a79bf73992086394 to your computer and use it in GitHub Desktop.
Save esabook/4f3c37fe0046f245a79bf73992086394 to your computer and use it in GitHub Desktop.
Custom EditTextView with vector compoundDrawable support, emulate app:drawableLeftCompat (LEFT, RIGHT, TOP, BOTTOM) as for non AndroidX project
package ***
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.widget.AppCompatEditText;
import android.util.AttributeSet;
import android.view.Gravity;
import ***.R;
public class EditTextCompat extends AppCompatEditText {
public EditTextCompat(Context context) {
super(context);
}
public EditTextCompat(Context context, AttributeSet attrs) {
super(context, attrs);
initDrawableDecor(context, attrs);
}
public EditTextCompat(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initDrawableDecor(context, attrs);
}
void initDrawableDecor(Context ctx, AttributeSet attrs) {
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.EditTextCompat);
try {
int idLeft = a.getResourceId(R.styleable.EditTextCompat_drawableLeftCompat, 0);
int idTop = a.getResourceId(R.styleable.EditTextCompat_drawableTopCompat, 0);
int idRight = a.getResourceId(R.styleable.EditTextCompat_drawableRightCompat, 0);
int idBottom = a.getResourceId(R.styleable.EditTextCompat_drawableBottomCompat, 0);
Drawable drwLeft = getDrawable(idLeft);
Drawable drwTop = getDrawable(idTop);
Drawable drwRight = getDrawable(idRight);
Drawable drwBottom = getDrawable(idBottom);
Drawable[] drawable = getCompoundDrawables();
drawable[0] = drwLeft != null ? drwLeft : drawable[0];
drawable[1] = drwTop != null ? drwTop : drawable[1];
drawable[2] = drwRight != null ? drwRight : drawable[2];
drawable[3] = drwBottom != null ? drwBottom : drawable[3];
setCompoundDrawablesWithIntrinsicBounds(drawable[0], drawable[1], drawable[2], drawable[3]);
setGravity(Gravity.CENTER_VERTICAL);
} catch (Exception e) {
e.printStackTrace();
}
a.recycle();
}
Drawable getDrawable(@DrawableRes int id) {
Drawable d = null;
try {
d = ResourcesCompat.getDrawable(getResources(), id, null);
} catch (Exception ignore) {
}
return d;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment